我基本上想在 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/