【发布时间】:2010-04-08 00:27:18
【问题描述】:
我尝试在 main 中执行 fork() 和管道,它工作得非常好,但是当我尝试在一个函数中实现它时,由于某种原因我没有得到任何输出,这是我的代码:
void cmd(int **pipefd,int count,int type, int last);
int main(int argc, char *argv[]) {
int pipefd[3][2];
int i, total_cmds = 3,count = 0;
int in = 1;
for(i = 0; i < total_cmds;i++){
pipe(pipefd[count++]);
cmd(pipefd,count,i,0);
}
/*Last Command*/
cmd(pipefd,count,i,1);
exit(EXIT_SUCCESS);
}
void cmd(int **pipefd,int count,int type, int last){
int child_pid,i,i2;
if ((child_pid = fork()) == 0) {
if(count == 1){
dup2(pipefd[count-1][1],1); /*first command*/
}
else if(last!=1){
dup2(pipefd[count - 2][0],0); /*middle commands*/
dup2(pipefd[count - 1][1],1);
}
else if(last == 1){
dup2(pipefd[count - 1][0],0); /*last command*/
}
for(i = 0; i < count;i++){/*close pipes*/
for(i2 = 0; i2 < 2;i2++){
close(pipefd[i][i2]);
}}
if(type == 0){
execlp("ls","ls","-al",NULL);
}
else if(type == 1){
execlp("grep","grep",".bak",NULL);
}
else if(type==2){
execl("/usr/bin/wc","wc",NULL);
}
else if(type ==3){
execl("/usr/bin/wc","wc","-l",NULL);
}
perror("exec");
exit(EXIT_FAILURE);
}
else if (child_pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
}
}
我检查了文件描述符,它打开了正确的,不确定是什么问题 可能是..
编辑:我解决了问题,但我有子进程,哪种方式最好等待子进程,while(wait(NULL)!=-1);但这挂了
【问题讨论】:
-
您不能将
pipefd[3][2](传统的二维数组)作为int**传递,参见c-faq.com/aryptr/ary2dfunc3.html