我尝试在 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
不是一个 int**
,它是一个 int[3][2]
,所以当你通过它到 cmd
,你得到垃圾。您的编译器应该在每次调用 cmd()
时给您一个警告,例如:
warning: passing argument 1 of 'cmd' from incompatible pointer type
如果不是,请提高警告级别。
的确,数组会退化为指向其第一个元素的指针,因此您可以将一维数组传递给需要指针的函数,但这仅适用于数组的第一个维度。特别是,二维数组不会退化为指向指针的指针。它仅在第一级衰减,因此 pipefd
可以衰减为类型 int (*)[2]
,它被读作“指向 的数组 2 的指针”整数
”
所以,cmd
的正确写法是这样的:
void cmd(int (*pipefd)[2],int count,int type, int last)
关于c - 用管道 fork ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2596799/