我有一个程序,需要启动其他程序,可能用文件和管道替换其stdio。尽管子进程确实从源管道获取了它的I / O,但似乎“起作用”,但是不幸的是,这也导致了挂起。子进程似乎从未获得EOF。
这里是代码的最小复制,为什么在打印"Hello World\n"后仍然挂起?
#include
#include
#include
#include
#include
#include
int main(int argc, char *argv[]) {
switch (pid_t pid = fork()) {
case 0: {
// in child
// replace the child's stdin with whatever filename is given as argv[1]
freopen(argv[1], "r+b", stdin);
// construct an argv array for to exec, no need for anything except
// argv[0] since we want it to use stdin
char path[] = "/bin/cat";
char *args[] = {path, NULL};
// run it!
execv(args[0], args);
abort(); // we should never get here!
}
case -1:
// error
return -1;
default: {
// in parent, just wait for the sub-process to terminate
int status;
const auto r = waitpid(pid, &status, __WALL);
if (r == -1) {
perror("waitpid");
return -1;
}
break;
}
}
}
# runs printf creating a pipe, which is this passed as the argv of my test program
./test >(printf "Hello\n")
0
投票
./test
切换到>(...)至
freopen(argv[1], "rb", stdin);
请勿使用r+。您只从文件中读取,因此将其设为r。