4.1 概述
管道只在亲缘进程间使用,FIFO在任意进程间使用
4.2 管道
#include <unistd.h> int pipe(int fd[2])
fd[0]用来读管道,fd[1]用来写管道
1)命令who | sort | lp中的管道:
2)管道实现文件服务器与客户端:
#include <unistd.h> #include <stdio.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <error.h> #define MAXLINE 1024 void client(int readfd,int writefd); void server(int readfd,int writefd); int main() { int fd1[2]; int fd2[2]; pipe(fd1); pipe(fd2); int pid; if( (pid = fork()) < 0) { fprintf(stderr,"fork error "); exit(-1); } if(pid > 0) { close(fd1[1]); close(fd2[0]); server(fd1[0],fd2[1]); exit(0); } close(fd1[0]); close(fd2[1]); client(fd2[0],fd1[1]); waitpid(pid,NULL,0); exit(0); } void client(int readfd,int writefd) { size_t len; char buf[MAXLINE]; fgets(buf,MAXLINE,stdin); len = strlen(buf); if(buf[len-1] == ' ') --len; write(writefd,buf,len); while( (len = read(readfd,buf,MAXLINE)) > 0) write(STDOUT_FILENO,buf,len); } void server(int readfd,int writefd) { char buf[MAXLINE]; ssize_t n; if( (n = read(readfd,buf,MAXLINE)) ==0) { fprintf(stderr,"error "); exit(-1); } buf[n] = '