我试图编写一个带有两个程序的C程序,并将stdin / out重定向到每个程序中:
stdin:程序B的标准输出
stdin:程序A的标准输出
我尝试过使用两根烟斗(并关闭未使用的末端),但我得到了Broken Pipe [Errno 32]
。是否有可能产生循环依赖"像这样用C管道?
为了测试我的C程序,我编写了两个简单的程序(A和B)。我彻底测试了A和B.
程序A做了4件事:
计划B做了三件事:
我的C程序将两个程序作为输入,并尝试将它们连接在一起,如上所述。不幸的是,我得到了Broken Pipe [Errno 32]
。
计划A:
#!/usr/bin/python3
import sys
def main():
# read from some source other than stdin
with open("test_in", "r") as in_file:
inbuf = in_file.read()
# write the buffer to stdout
print(inbuf)
# read from stdin
outbuf = sys.stdin.read()
# write the buffer to the secondary source
with open("test_out", "w+") as w_file:
w_file.write(outbuf)
if __name__ == "__main__":
main()
计划B:
#!/usr/bin/python3
import sys
def transform(buf):
return "".join(list(reversed(buf)))
def main():
inbuf = sys.stdin.read()
print(transform(inbuf))
if __name__ == "__main__":
main()
我的C计划(重要的部分):
for (int i = 0; i < 2; i++) {
pids[i] = fork();
if (pids[i] == -1) {
fprintf(stderr, "Failed to fork off process %d.\n", i);
exit(1);
}
if (pids[i] == 0) {
// child
if (i == 0) {
dup2(fds[0], 0);
dup2(fds[3], 1);
close(fds[1]);
close(fds[2]);
execvp(program_a, (char*[]){program_a, (char*)(NULL)});
fprintf(stderr, "execvp %s failed.\n", program_a);
exit(1);
} else if (i == 1) {
dup2(fds[2], 0);
dup2(fds[1], 1);
close(fds[0]);
close(fds[3]);
execvp(program_b, (char*[]){program_b, (char*)(NULL)});
fprintf(stderr, "execvp %s failed.\n", program_b);
exit(1);
} else {
fprintf(stderr, "ERROR: Line %d This should never happen.\n", __LINE__);
exit(1);
}
} else {
// parent
}
}
close(fds[0]);
close(fds[1]);
close(fds[2]);
close(fds[3]);
int statuses[2];
waitpid(pids[0], &statuses[0], 0);
waitpid(pids[1], &statuses[1], 0);
fds [0]和fds [1]分别是第一个管道的读写端。 fds [2]和fds [3]是第二种。