我有一个关于子进程行为的问题。这个测试程序的目的是运行Linux命令echo Hello | wc
使用管道。
我的命令不起作用,结果调用了错误的 c 字符串。
预期输出是:
command 0
echo
command 1
wc
但是,我得到:
command 0
echo
command 1
Hello
我只有在注释掉时才能得到预期的输出
execvp(),当子进程没有退出时。
这是测试函数:
int test(pid_t id[])
{
int i;
int pipefd[2];
char *cat_args[] = {"echo","Hello", NULL};
char *grep_args[] = {"wc", NULL};
char **arr[] = {cat_args,grep_args};
// make a pipe
pipe(pipefd);
for(i = 0; i < 2; i++){
id[i] = fork();
if (id[i] == -1){
printf("Unable to create child process");
fprintf(stderr,"fork() failed to spawn child process");
exit(1);
}
else if (id[i] == 0){
printf("command ");
printf("%d\n",i);
if (i == 0){
dup2(pipefd[0],STDIN_FILENO);
}
else if (i == 1){
dup2(pipefd[1],STDOUT_FILENO);
}
// Close pipes for child processes
close(pipefd[0]);
close(pipefd[1]);
printf("%s\n",*arr[i]);
//To simply and simulate problem, can replace execvp() with exit(0);
execvp(*arr[i],arr[i]);
}
}
// Close pipes of parent process close(pipefd[0]);
close(pipefd[1]);
return 0;
}
这是主要功能:
int main(int argc, char **argv)
{
pid_t id[2];
test(id);
int status;
waitpid(id[0],&status,0);
waitpid(id[1],&status,0);
return 0;
}