[英]Piping the output of one child process as the input of another child process
I'm trying to run ls -l with sort so sort can be applied to ls -l 我正在尝试以排序方式运行ls -l,因此可以将sort应用于ls -l
but when i run it it doesn't give the same output as ls -l | 但是当我运行它时,它不会提供与ls -l |相同的输出。 sort I'm not sure why I understand piping,dupe,fork,close somewhat but still confused on how to apply them to make this work
排序我不确定为什么我了解管道,双面胶,叉形,封闭式的一些东西,但仍然对如何应用它们来使这项工作感到困惑
int pipe1[2];
// will hold the ids of our forks
pid_t pid1;
// will hold the ids of our forks
pid_t pid2;
pipe(pipe1);
// call our child process
pid1 = fork();
if (pid1 == 0)
{
// dealocate the 1 of
close(1);
// duplicate the write end
dup(pipe1[1]);
// close the read end
close(pipe1[0]);
// close the write end
close(pipe1[1]);
printf("child1 executing ls \n");
execl("/bin/ls", "ls", 0, 0);
perror("execl error");
}
else
{
wait(&pid1);
pid2 = fork();
if (pid2 == 0)
{
close(0);
dup(pipe1[0]);
close(pipe1[0]);
close(pipe1[1]);
printf("child2 executing sort \n");
execl("/bin/sort", "sort",0, 0);
perror("execl error");
}
else
{
wait(0); //wait for children
}
}
}
add below into else { [here] wait(0); 将以下内容添加到else {[here] wait(0); }
}
close(pipe1[0]);
close(pipe1[1]) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.