c++ - 在 C 中,当管道输入到另一个程序时,它无法打开

标签 c++ c fork pipe fopen

我基本上想在 C 中实现这一点:echo 'some string' | foo 其中 foo 写入文件 file1.txt。运行 foo 使其阻塞并等待来自 stdin 的输入,然后写入 file1.txt。我成功地通过 stdin 将数据发送到 foo,但是在使用 C 管道时 foo 无法打开本地文件。

这是我所做的:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {

    FILE *stream;
    int fds[2];
    int status;
    pid_t pid;
    char *cmd[] = { "foo", NULL };

    pipe(fds);
    pid = fork();

    if (pid < 0) {
        fprintf(stderr, "Fork failed\n");
        return 1;
    }
    if (pid > 0) {
        // Parent process
        close(fds[0]);
        stream = fdopen(fds[1], "w");
        fprintf(stream, "some string\n");
        fflush(stream);
        close(fds[1]);
        waitpid(pid, &status, 0);
        if (WIFEXITED(status) == 0 || WEXITSTATUS(status) < 0)
            return 1;
    }
    else {
        // Child process
        close(fds[1]);
        dup2(fds[0], STDIN_FILENO);

        execv("foo", cmd);
        return 1;
    }

    return 0;
}

在内部,foo 对本地文件进行了 fopen 调用,但失败并出现错误 14:EFAULT。我也试过只使用 popen/pclose 而不是 fork/pipe/dup2/execv 来做到这一点。

我该怎么做才能使这项工作成功?

最佳答案

假设 foo 位于 PATH 目录中,Yuu 可能需要使用 execvp。除此之外,您可能需要在 execv("/full/path/to/foo", cmd);

中提供完整路径

关于c++ - 在 C 中,当管道输入到另一个程序时,它无法打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12814268/

相关文章:

python - 使用 Python/C API 将 Python 列表传递给 C 函数

c - 函数指针在实际应用中的用法

linux - fork() copy-on-write 是一种稳定的暴露行为,可以用来实现只读共享内存吗?

c++ - 将 cv::Mat 转换为 IplImage*

c - 编译调用外部库的 cython 代码时出现链接错误

c++ - 使用 OpenCV (C++) 在 Xcode 中访问网络摄像头

c - 如何中断一个进程并稍后继续?

c - pipe - fork - c - 为什么程序没有任何错误而没有响应?

c++ - 递减原子计数器 - 但 <only> 在一个条件下

c++ - ASIO 聊天 session 类在销毁时抛出异常 : C++ ASIO