日期:2014-05-16  浏览次数:20583 次

为什么父进程一直阻塞呢,
C/C++ code

  1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<sys/types.h>
  4 int main()
  5 {
  6     int fd[2];
  7     pid_t pid1,pid2;
  8     char *arg_net[] = {"netstat","-lant",NULL};
  9     char *env_net[] = {"PATH=/bin",NULL};
 10     char *arg_grep[] = {"grep","22",NULL};
 11     char *env_grep[] = {"PATH=/bin",NULL};
 12     if(pipe(fd) != 0)
 13         exit(1);
 14     if((pid1 = fork()) == 0){
 15         printf("pid1 = %d\n",getpid());
 16         close(1);
 17         dup2(fd[1],1);
 18         close(fd[0]);
 19         close(fd[1]);
 20         execve("/bin/netstat",arg_net,env_net);
 21         exit(0);
 22     }else if(pid1 < 0 ){
 23         printf("fork error\n");
 24         exit(1);
 25     }
 26 
 27 
 28     if((pid2 = fork()) == 0){
 29         printf("pid2 = %d\n",getpid());
 30         close(0);
 31         dup2(fd[0],0);
 32         close(fd[1]);
 33         close(fd[0]);
 34         execve("/bin/grep",arg_grep,env_grep);
 35         exit(0);
 36     }else if(pid2 < 0){
 37         printf("fork error\n");
 38         exit(2);
 39     }
 40     printf("parent = %d\n",getpid());
 41     waitpid(pid1,NULL,0);
 42     waitpid(pid2,NULL,0);
 43     return 0;
 44 }


程序不能正常退出,父进程一直阻塞,求指点

------解决方案--------------------
别幼稚了,麻烦40行之前插入close(fd[1]);