pipe的特点:
1,只能用在相关进程间进行通信
2,生存期是“进程持续的”
3,pipe在进程间通信时,pipe中的数据保存在“系统内核中”
库函数:
#include <unistd.h>
int pipe(int pipefd[2]);
下面 给出的是一个基于PIPE 实现的client-server简单程序,client从标准输入读取文件名发送给server,server返回文件内容,client显示在标准输出main: 1 #include "../ch04.h" 2 extern void client(int,int); 3 extern void server(int,int); 4 int main() 5 { 6 int pipe1[2],pipe2[2]; 7 8 pid_t childpid; 9 pipe(pipe1); 10 pipe(pipe2); 11 12 if((childpid = fork())==0)//child process:client 13 { 14 close(pipe1[0]);//close read of pipe1 15 close(pipe2[1]);//close write of pipe2 16 client(pipe2[0],pipe1[1]); 17 exit(0); 18 } 19 else if(childpid>0)//parent process:server 20 { 21 close(pipe1[1]);//close write of pipe1 22 close(pipe2[0]);//close read of pipe2 23 24 server(pipe1[0],pipe2[1]); 25 int status; 26 waitpid(childpid,&status,0); 27 printf("child status=%d/n",status); 28 exit(0); 29 } 30 else 31 { 32 perror("fork() error"); 33 exit(0); 34 } 35 } client: 1 #include "../ch04.h" 2 3 void client(int rfd,int wrd) 4 { 5 char filename[MAXLINE]; 6 char buf[MAXLINE]; 7 size_t len; 8 ssize_t n; 9 fgets(filename,sizeof(filename),stdin); 10 len = strlen(filename); 11 if(filename[len-1]=='/n')//the len of read-filename including '/n' don't exceed MAXLINE 12 len --; 13 write(wrd,filename,len); 14 15 while((n = read(rfd,buf,MAXLINE))!=0) 16 { 17 write(STDOUT_FILENO,buf,n); 18 } 19 } server: 1 #include "../ch04.h" 2 3 void server(int rfd,int wfd) 4 { 5 char buf[MAXLINE+1]; 6 ssize_t n; 7 n = read(rfd,buf,sizeof(buf)); 8 buf[n]='/0'; 9 10 int filefd = open(buf,O_CREAT|O_RDONLY,0777); 11 if(filefd < 0) 12 { 13 snprintf(buf+n,sizeof(buf)-n,": can't open %s/n",strerror(errno)); 14 } 15 else 16 { 17 while((n = read(filefd,buf,MAXLINE)) >0) 18 write(wfd,buf,n); 19 close(filefd); 20 } 21 } 。
另外:函数
FILE * popen(const char * command,const char *type);
根据command执行shell命令,并将标准输入和标准输出重定向为pipe[2]。type为“r”或"w"。
返回pipe的FILE指针。
int pclose(FILE *fp);
关闭popen返回的FILE*fp。