这段代码基本上是二叉树的一小部分,节点是进程,它应该按顺序遍历树,将 num1 传递到左子树等。这段代码只是创建一个左子树并只执行 ./tpipe 这是这个的可执行文件再次编码。当我们像“./tpipe 0”这样传递它时,scanf似乎从用户那里获取输入,而不是之前处理的 printfed 字符串。我该如何解决?我应该使用 dup2 而不是读写等,因为在开始时再次启动了 fieldsp。
这是精简版:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <assert.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{
if (argc < 2)
{
fprintf(stderr, "NEED MORE ARGUMENT\n");
return 1;
}
int curDepth = atoi(argv[1]);
int filedp[2];
pipe(filedp);
if (curDepth != 0)
{
char buf[100];
scanf("%s", buf);
fprintf(stderr, "buf is: %s\n", buf);
}
if (curDepth < 1)
{
int fd = fork();
if (fd == 0)
{
close(filedp[0]);
dup2(filedp[1], STDOUT_FILENO);
dup2(filedp[0], STDIN_FILENO);
printf("Example\n");
char *k[] = {"./tpipe", "1", NULL};
execvp("./tpipe", k);
}
else
{
wait(NULL); // parent
}
}
else
{
fprintf(stderr, "IT IS LEAF!\n");
}
return 0;
}
我不知道我理解是否正确,但似乎你希望孩子在其标准输入上阅读
"Example\n"
?
然后你应该将其写入管道。你应该在parent过程中写下:
if (fd == 0)
{
// Child process
close(filedp[1]); // We don't need the write-end of the pipe here
dup2(filedp[0], STDIN_FILENO); // Copy the read-end of the pipe to standard input
// Then execute the program
char *k[] = {"./tpipe", "1", NULL};
execvp("./tpipe", k);
}
else
{
// Parent process
close(filedp[0]); // We don't need the read-end of the pipe here
write(filedp[1], "Example\n", 8); // Write to the pipe
// The child process will read the above from its standard input
// Wait for the child process to exit
wait(NULL);
}