练习:使用管道实现兄弟进程间通信。 兄:ls 弟: wc -l 父:等待回收子进程。 要求,使用“循环创建N个子进程”模型创建兄弟进程,使用循环因子i标示。注意管道读写行为
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
int main()
{
int ret,i,num =
2;
int fd[
2];
pid_t pid,w_pid;
int status;
if ( -
1 == (ret = pipe(fd) ))
{
perror(
"pipe faile");
exit(
1);
}
for(i =
1; i <
3; i++)
{
pid = fork();
if(
0 == pid)
break;
}
if(
0 == pid )
{
if(
1 == i)
{
close(fd[
0]);
dup2(fd[
1],STDOUT_FILENO);
execlp(
"ls",
"ls",NULL);
}
if(
2 == i)
{
close(fd[
1]);
dup2(fd[
0],STDIN_FILENO);
execlp(
"wc",
"wc",NULL);
}
}
else
{
#if 0
close(fd[
0]);
close(fd[
1]);
for(i=
0; i<
2; i++)
wait(NULL);
#endif
#if 1
do
{
close(fd[
0]);
close(fd[
1]);
w_pid = waitpid(-
1,NULL,WNOHANG);
if(w_pid >
0)
num--;
}
while(num>
0);
printf(
"finished\n");
#endif
}
return 0;
}