我正在try 用C语言编写一个支持多管道进程处理的shell ,这取决于用户给出的独立进程的数量,每个进程都用"|"符号分隔.shell 将进程的数量Forking 到每个进程的子进程中.
下面是一个例子:
texto1.txt = "Isto é o Texto 1"
$ cat texto1.txt | grep -c Isto
结果:1
但我在子元素之间的沟通以及最终与父母进程的沟通方面遇到了困难.
下面是我当前的execpipe
函数代码,它执行管道进程,argv1
和argv2
是由用户输入给出的两个单独的进程:(示例:ls -l | wc -l
)
int execpipe(char ** argv1, char ** argv2)
{
int fds[2];
pipe(fds);
int i;
pid_t p1, p2;
p1 = fork();
if (p1 == -1)
{ // error
char * error = strerror(errno);
printf("error fork!!\n");
return 1;
}
if (p1 == 0)
{ // child process
close(fds[0]);
dup2(fds[1], STDOUT_FILENO);
close(fds[1]);
if(execvp(argv1[0], argv1)<0){ // run command AFTER pipe character in userinput
char * error = strerror(errno);
printf("unknown command\n");
return 0;
}
}
else
{ // parent process
p2 = fork();
if(p2==0){
close(fds[1]);
dup2(fds[0], STDIN_FILENO);
close(fds[0]);
if(execvp(argv2[0], argv2)<0){ // run command AFTER pipe character in userinput
char * error = strerror(errno);
printf("unknown command\n");
return 0;
}
}else{ //Parent waits for both of it's children
wait(NULL);
wait(NULL);
}
}
}