如下是Pipe的一个简单的例子。管道的通信是单项的。只能一端写,一端读。管道通信只能在有共同祖先的两个进程之间。在两个进程中,进行数据传送。pipe(fd)创建管道,fd【0】作为read端,fd【1】作为写入端。当fd[1]不存在的时候,认为已经读到结尾,read返回0.如果fd[1]存在,写入数据后,将写入端关闭,但是数据一直存在,直到读出。数据总是写在管道的尾部,而读的时候,则是从头部开始读取。#include #include #include #include #include int fd[2];
int main() {pid_t pid; char buffer[PIPE_BUF]; memset(buffer, 0, PIPE_BUF); if(pipe(fd) < 0) {printf("Failed to create a pipe!!\n");return 0;}if (0 == (pid = fork())) {printf("sub pid = %d\n", pid);close(fd[1]);// close the write pipesleep(1);// has time for
write if (read(fd[0], buffer, 32) > 0){ printf("receive data from server, %s\n!!",buffer);}close(fd[0]);} else {printf("master pid = %d\n", pid);close(fd[0]);// close the write pipeif (-1 != write(fd[1], "Hello World", strlen("Hello World"))) { // write data
to pipeprintf("send data to cline hello world!!!\n");}close(fd[1]);// close writewaitpid(pid, NULL, 0);}return 1;}