天天看点

Linuxc 进程间通信之匿名管道2 兄弟间通信

利用匿名管道实现兄弟进程间通信,要求

1.兄进程发送字符串“This is elder brother ,pid is (兄进程进程号)”给弟进程;

2.弟进程收到兄进程发送的数据后,给兄进程回复“This is younger brother ,pid is(第进程进程号)”;

源代码:

#include <unistd.h>

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

int main(int argc,char *argv[])

{

  char str1[50],num1[50],str2[50],num2[50];

        int fd1[2],fd2[2];//0用于读,1用于写

        pipe(fd1);

     pipe(fd2);

        int pid=fork();

        if(pid==0)

        {

  close(fd1[0]);

  close(fd2[1]);

                //char str[50],num[10];

  strcpy(str1,"This is elder brother,pid is ");

  sprintf(num1,"%d",getpid());

  strcat(str1,num1);

  write(fd1[1],str1,50);

                read(fd2[0],str2,50);  

   printf("\n%s\n",str2);

        }

        else if(pid>0)

        {

  int n=fork();

  if(n==0)

  {

   close(fd1[1]);

                 close(fd2[0]);

                 //char str[50],num[10];

                 read(fd1[0],str1,50);

                 printf("\n%s\n",str1);

   strcpy(str2,"This is younger brother,pid is ");

   sprintf(num2,"%d",getpid());

                 strcat(str2,num2);

   write(fd2[1],str2,50);

  }

  else if (n>0)

  {

   close(fd1[0]);

                 close(fd2[1]);

   close(fd2[0]);

                 close(fd1[1]);   }

         }

 else

 {

  perror("fork error;");

 }      

        return 0;

匿名管道相关函数请参考:点击打开链接

https://blog.csdn.net/qq_37192076/article/details/80456769