c - 如何在 c 中结束重定向的 execlp

标签 c pipe exec posix

我尝试重定向 exec 函数输入,使用管道输出结果。这段代码工作正常,但我无法退出下面的 execlp 函数,它总是需要新的输入,但我只想运行一次。如何在第一次输入后停止它。

#include    <sys/types.h>
#include    <sys/stat.h>
#include    <unistd.h>
#include    <fcntl.h>
#include    <stdio.h>
#include    <stdlib.h>
#include    <errno.h>
#include    <string.h>
#include    <signal.h>
#define ERR_EXIT(m) \
    do { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while(0)

int main(int argc, char *argv[])
{
    int chi_pipe[2], par_pipe[2];
    if (pipe(chi_pipe) == -1 || pipe(par_pipe) == -1)
        ERR_EXIT("pipe error");
    pid_t pid;
    pid = fork();
    if (pid == -1)
        ERR_EXIT("fork error");

    if (pid == 0)
    {
        close(chi_pipe[0]); // I don't read in channel 1
        close(par_pipe[1]); // I don't write in channel 2
        close(STDIN_FILENO);
        dup(par_pipe[0]);
        execlp("tr", "tr", "/a-z/", "/A-Z/", NULL);
        close(chi_pipe[1]);
        close(par_pipe[0]);
        _exit(0);
    }

    close(par_pipe[0]);
    close(chi_pipe[1]);
    write(par_pipe[1], "haha\n", 5);
    char buf[3024] = {0};
    read(chi_pipe[0], buf, 1024*3);
    printf("buf=%s", buf);
    printf("\n");
    close(par_pipe[1]);
    close(chi_pipe[0]);
    return 0;
}

最佳答案

我想你想要这个。

将关闭位置向上移动,以便读取可以知道它不会再得到了。

    write(par_pipe[1], "haha\n", 5);
    close(par_pipe[1]);

你似乎也错过了子段中标准输出的复制,

关于c - 如何在 c 中结束重定向的 execlp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27457325/

相关文章:

c - 需要帮助调试 C 代码

java - Runtime.getRuntime().exec 可以是类路径资源吗?

c - 从主要参数执行程序

linux - 使用 sed 过滤管道

linux - Node 生成 std​​out.on 数据延迟

linux - 将标准输入/输出重定向到替代命令

c++ - 我很困惑如何在这个使用 fork() 克隆进程的示例函数中处理这个 execvp()

C 将 char** 指向另一个起始位置?

c - 在 main 中声明的函数原型(prototype) - 最佳实践?

c - 为什么我在运行我的快速排序算法代码时收到 fastsort.exe 已停止工作并出现错误 255 <0xff>?我正在使用代码块