使用unnamed pipes和打开与使用文件大同小异。这在UNIX相关的操作系统里是非常普遍的。Linux里的pipes是单方通讯的机制。当你打开一个unnamed pipe的时候,你打开了一对filedescriptor,其中一个用来读,而另一个用来写。要打开一个pipe,使用pipe功能并传递两个int型的数组。
代表性地,使用pipes的顺序应该是:
1. 创建pipe
2. 调用派生
3. 双亲写pipe,孩子读pipe (反之亦然)
4. 传递end-of-file字符
5. 关闭pipe
这个的工作原理是子进程在调用派生的时候从母进程获得了打开文件描述符。
下面是一个unnamed pipe的例子:
int main(){
intdscs[2];
pid_t child;
char in = 0;
pipe(dscs);
child = fork();
if (pid != 0){//this is the
parent process
while(!eof(dscs[0])){
read(dscs[0],
&in, 1);
putchar(in);
}
waitpid(child);
}else{//this is the child process
dup2(dscs[1], STDOUT_FILENO);//redirect
stdout
puts("starting child
process
");
system("/bin/ls;cat /dev/null");
}
return 0;
}
pipes的优点之一是它们的同步非常准确。因为pipes的缓冲器相当有限,一个进程在读或写pipes的时候能够超过另一个进程。这时,这个跑得最快进程将停滞,等待其他的进程。
使用pipes的主要缺点是,进程必须具备亲子关系。你不能简单地传递无关的进程文件描述符。