linux c 进程 pipe 通信代码分析

[root@luozhonghua 04]# cat ex04-3-pipe02.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>


int main(void){
   int result=-1;
   int fd[2],nbytes;
   pid_t pid;
   char string[]="hello,pipe";
   char readbuffer[80];


   int *write_fd = &fd[1];  //可写
   int *read_fd = &fd[0];  //read


   result = pipe(fd);  //create pipe


   if(-1 == result){
     printf("create pipe faile");
     return -1;
    }


   pid=fork(); //分叉程序


   if(-1 == pid){
    printf("fork 进程失败\n");
    return -1;
   }


   if(0 == pid ){
     close(*read_fd);
     /*向管道端写入字符*/
     result=write(*write_fd,string,strlen(string));


   }else{
     close(*write_fd);
     /* read pipe data */
     nbytes=read(*read_fd,readbuffer,sizeof(readbuffer));
     printf("接收到%d 个数据,内容:%s \n",nbytes,readbuffer);
     printf("sizeof(readbuffer) =  %d\n",sizeof(readbuffer));
   }


   return 0;

}


--------------测试结果

[root@luozhonghua 04]# ./ex04-3-pipe02
接收到10 个数据,内容:hello,pipe
sizeof(readbuffer) =  80


你可能感兴趣的:(linux,进程通信,pipe)