管道看上去也就创造了两个文件描述符,能够读写,好像没能体现出应有的价值,但是假如是要进程间通信,传递数据的时候,只要管道打开的两个文件描述符存在,通过调用fork创建子进程,那么两个进程可以通过管道传递数据,才是真正有用的时候
调用pipe之后,接着调用fork,这样就创建了由主到子(或者子到主)的通道,但是fork之后进程做什么就决定了数据流的方向,下面的简单例子就是从子进程到主进程的方向
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#define MAXSIZE 20
int main(){
int filedes[2];
char *message = "Hello world";
char buffer[MAXSIZE];
pid_t pid;
memset(buffer, 0, sizeof(buffer));
if (pipe(filedes)){
printf("pipe create failed!\n");
exit(1);
}
if ((pid = fork()) < 0){
printf("fork failed!\n");
exit(1);
} else if (pid == 0){
write(filedes[1], message, strlen(message));
printf("Child have written: %d bytes\n", strlen(message));
} else {
read(filedes[0], buffer, MAXSIZE);
printf("Main have read message: %s\n", buffer);
}
return 0;
}
编译运行:
lihui@2015 $ ./a.exe Child have written: 11 bytes Main have read message: Hello world
这里没有进程等待,输出结果两进程次序未知
