我一直在尝试在c中实现以下命令:cat /etc/passwd扣减-f1-d:AC.26 sort
这是我目前掌握的密码。第一个管道工作正常,但第二个管道似乎根本不工作。
我一遍又一遍地检查了代码,但没有发现任何问题。有人能给我一个解决问题的建议吗?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int pipe_A[2];
int pipe_B[2];
pipe(pipe_A);
pipe(pipe_B);
pid_t pid_A, pid_B, pid_C;
if( !(pid_A = fork()) ) {
close(1); /* close normal stdout */
dup(pipe_A[1]); /* make stdout same as pipe_A[1] */
close(pipe_A[0]); /* we don't need this */
execlp("/bin/cat", "cat", "/etc/passwd" , NULL);
}
if( !(pid_B = fork()) ) {
close(0); /* close normal stdin */
dup(pipe_A[0]); /* make stdin same as pipe_A[0] */
close(pipe_A[1]); /* we don't need this */
close(1); /* close normal stdout */
dup(pipe_B[1]); /* make stdout same as pipe_B[1] */
close(pipe_B[0]); /* we don't need this */
execlp("/usr/bin/cut", "cut", "-f1", "-d:", NULL);
}
if( !(pid_C = fork()) ) {
close(0); /* close normal stdin */
dup(pipe_B[0]); /* make stdin same as pipe_B[0] */
close(pipe_B[1]); /* we don't need this */
execlp("/usr/bin/sort", "sort", NULL);
}
return 0;
}谢谢。
发布于 2015-02-26 00:36:48
问题是你到处都是漏水的FDs。注意,每次调用叉时,所有打开的管道都由子进程继承,但是带有dup‘’ed的管道不能正常工作。
例如,cat继承了pipe_B的读和写FDs。同样,sort继承了pipe_A的两个FDs。
正确的方法应该是(但我建议使用dup2() ):
int main(void)
{
int pipe_A[2];
int pipe_B[2];
pid_t pid_A, pid_B, pid_C;
pipe(pipe_A);
if( !(pid_A = fork()) ) {
close(pipe_A[0]); // A-read not needed here
close(1);
dup(pipe_A[1]);
close(pipe_A[1]); //do not pass A-write twice
execlp("/bin/cat", "cat", "/etc/passwd" , NULL);
}
close(pipe_A[1]); // A-write not needed anymore
pipe(pipe_B); //do not create this pipe until needed
if( !(pid_B = fork()) ) {
close(pipe_B[0]); // B-read not needed here
close(0);
dup(pipe_A[0]);
close(pipe_A[0]); //do not pass A-read twice
close(1);
dup(pipe_B[1]);
close(pipe_B[1]); //do not pass B-write twice
execlp("/usr/bin/cut", "cut", "-f1", "-d:", NULL);
}
close(pipe_A[0]); // A-read not needed anymore
close(pipe_B[1]); // B-write not needed anymore
if( !(pid_C = fork()) ) {
close(0);
dup(pipe_B[0]);
close(pipe_B[0]); // do not pass B-read twice
execlp("/usr/bin/sort", "sort", NULL);
}
close(pipe_B[0]); // B-read not needed anymore
return 0;
}如果您分析我的代码(如果我写得对),假设父进程只有FD0、1和2,那么每个execlp()都会得到精确的3个FDs、0、1和2。
https://stackoverflow.com/questions/28732195
复制相似问题