Linux高级编程基础——进程间通信之匿名管道

进程间通信之匿名管道

  1. 利用匿名管道实现父子进程间通信,要求
  2. 父进程发送字符串“hello child”给子进程;
  3. 子进程收到父进程发送的数据后,给父进程回复“hello farther”;
  4. 父子进程通信完毕,父进程依次打印子进程的退出状态以及子进程的pid。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

int main()
{
  int fd[2];
  char buf[100];
  int w , status , i ;
  pid_t pid;
  pipe (fd) ;   //创建匿名管道
  pid = fork ();
  if  ( pid > 0 )  //创建子进程,通过该判断进入父进程中
   {
      close(fd[0]);   //关闭管道 读端
      write(fd[1], "hello child \n", 12);   //打开管道 写端,写入“hello child”
      w = wait(&status);     // 通过wait 函数得到子进程的结束时的返回值和 pid
      if (WIFEXITED(status))
        i = WEXITSTATUS(status);
      printf ("child's pid = %d ,exit status = %d \n", w,i);
   }
  if  (pid == 0)   //通过判断进入 子进程
   {
      close(fd[1]);   //关闭管道 写端
      if ((read(fd[0], buf, 13)) != 0)  //打开管道 读端 ,并把读到的数据存在 buf 数组中
         printf("hello father \n");
      exit (2);   //结束子进程 ,设置他的返回值为 2;
   }
return 0;
}

/*

程序实现是创建 管道还是先创建 子进程 ?
先创建 管道 再 创建 子进程

*/

猜你喜欢

转载自blog.csdn.net/qq_40663274/article/details/83926262