unix编程——管道
管道函数
#inlcude <unistd.h>
int pipe(int fd[2])
上图来自unix网络编程卷二,描述了父子进程通过两个管道进行数据通信。
一个简单父子进程通信的例程:
pipe.h:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void server(int rd,int wr)
{
char buff[100];
ssize_t n;
if((n = read(rd,buff,100)) == 0){
printf("no chars\n");
return;
}
buff[n] = '\0';
printf("%s\n",buff);
write(wr,"Server got it\n",14);
}
void client(int rd,int wr)
{
int n;
char buff[100];
write(wr,"Hello,Server\n",13);
while((n = read(rd,buff,100)) > 0){
buff[n] = '\0';
printf("%s\n",buff);
}
}
int main()
{
int fd1[2];
int fd2[2];
pipe(fd1);
pipe(fd2);
pid_t cldp;
if((cldp = fork()) == 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(cldp,NULL,0);
exit(0);
}