#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];//读接口文件描述符,注意哪个是读,哪个是写 result=pipe(fd);//创建一个管道 if(result==-1) { printf("pipe create error\n"); return -1; } pid=fork();//创建一个子进程 if(pid==-1) { printf("fork error\n"); return -1; } if(pid==0) { close(*read_fd);//注意管道的工作方式为半双工 result=write(*write_fd,string,strlen(string));//写到管道 return 0; } else { close(*write_fd); nbytes=read(*read_fd,readbuffer,sizeof(readbuffer));//从管道中读取 printf("recieved %d date , contain : \"%s\"\n",nbytes,readbuffer); } return 0; }
这是一个进程间通过管道进行通信的例子
从这个例子中我们可以看到,子进程通过管道给父进程发送了“hello , pipe”,管道通信中要注意源代码中标注的一些细节。