Linux下进程间的通信——管道


  1. #include <stdio.h>   
  2. #include <stdlib.h>   
  3. #include <string.h>   
  4. #include <unistd.h>   
  5. #include <sys/types.h>   
  6. int main(void)  
  7. {  
  8.   int result=-1;  
  9.   int fd[2],nbytes;//数组用来存放管道两端的文件描述符   
  10.   pid_t pid;  
  11.   char string[]="hello , pipe";//要发送的内容   
  12.   char readbuffer[80];  
  13.   int *write_fd=&fd[1];//写接口文件描述符,本例给子进程调用   
  14.   int *read_fd=&fd[0];//读接口文件描述符,www.bkjia.com注意哪个是读,哪个是写   
  15.   result=pipe(fd);//创建一个管道   
  16.   if(result==-1)  
  17.   {  
  18.     printf("pipe create error\n");  
  19.     return -1;  
  20.   }  
  21.   pid=fork();//创建一个子进程   
  22.   if(pid==-1)  
  23.   {  
  24.     printf("fork error\n");  
  25.     return -1;  
  26.   }  
  27.   if(pid==0)  
  28.   {  
  29.     close(*read_fd);//注意管道的工作方式为半双工   
  30.     result=write(*write_fd,string,strlen(string));//写到管道   
  31.     return 0;  
  32.   }  
  33.   else  
  34.   {  
  35.    close(*write_fd);  
  36.    nbytes=read(*read_fd,readbuffer,sizeof(readbuffer));//从管道中读取   
  37.    printf("recieved %d date , contain : \"%s\"\n",nbytes,readbuffer);  
  38.   }  
  39.   return 0;  
  40. }  

这是一个进程间通过管道进行通信的例子

从这个例子中我们可以看到,子进程通过管道给父进程发送了“hello , pipe”,管道通信中要注意源代码中标注的一些细节。

相关内容