-
本文出自<svtter.github.io>
-
头文件: #include<unistd.h>
-
使用方法: int pipe(int chan[2]);
-
说明: pipe会建立管道,并将文件描述词通过chan返回。一般chan[0]为管道的读取端,chan[1]是写入端。
-
返回值: 成功返回0,失败返回-1,错误信息保存在errno中
-
错误信息:
- EMFILE 进程已用完文件描述词最大量。
- ENFILE 系统已无文件描述词可用。
- EFAULT 参数filedes数组地址不合法
/*============================================================================= # # Author: svtter - [email protected] # # QQ : 57180160 # # Last modified: 2014-11-21 16:20 # # Filename: 管道.c # # Description: # =============================================================================*/ #include <unistd.h> #include <signal.h> #include <stdio.h> char parent[] = "a message from parent"; char child[] = "a message from child"; int main () { int p2c[2], c2p[2]; int pid; char buf[100]; pipe(p2c); pipe(c2p); pid = fork(); if(pid > ) { close(c2p[]); close(p2c[1]); write(c2p[1], parent, sizeof(parent)); close(c2p[1]); read(p2c[], buf, 100); printf("%s\n", buf); close(p2c[]); } else if(pid == ) { close(p2c[]); close(c2p[1]); read(c2p[], buf, 100); printf("%s\n", buf); write(p2c[1], child, sizeof(child)); close(c2p[]); close(p2c[]); } return ; }
运行结果:
