pipe实现兄弟进程通信


pipe实现进程间通信,首先关闭第一个子进程的读入端,然后关闭第二个子进程的写入端

  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<unistd.h>
  4. int main()
  5. {
  6. int fd[2];
  7. pipe(fd);
  8. pid_t pid = fork();
  9. if(pid==0)
  10. {
  11. close(fd[0]);
  12. write(fd[1],"Hello",6);
  13. exit(0);
  14. close(fd[1]);
  15. }
  16. pid_t pid2 = fork();
  17. char buf[6]={0};
  18. if(pid2==0)
  19. {
  20. close(fd[1]);
  21. read(fd[0],buf,6);
  22. printf(buf);
  23. close(fd[0]);
  24. exit(0);
  25. }
  26. else if(pid2>0)
  27. {
  28. close(fd[0]);
  29. close(fd[1]);
  30. exit(0);
  31. }
  32. }





posted @ 2015-06-08 18:22  外禅内定,程序人生  阅读(449)  评论(0编辑  收藏  举报