《IPC管道pipe的简单使用.doc》由会员分享,可在线阅读,更多相关《IPC管道pipe的简单使用.doc(6页珍藏版)》请在三一办公上搜索。
1、IPC 管道pipe的简单使用 #include #include #include #include #include #define read_max_size 4096#define write_max_size 4096 * 32int main(int argc,char*argv) int pipe_fd2; pid_t pid; char r_bufread_max_size; char w_bufwrite_max_size; int writenum; int readnum; int readsum; int ret; ret = pipe(pipe_fd); if(ret
2、 0) readsum += readnum; printf(child : read %d bytes from pipe, sum = %dn, readnum, readsum); readnum = read(pipe_fd0,r_buf,read_max_size); printf(child : no more bytes to read from pipen); close(pipe_fd0); sleep(1); exit(0); else if(pid 0) / parent close(pipe_fd0); writenum = write(pipe_fd1,w_buf,
3、write_max_size); / 写操作会阻塞,直到所有数据写完 printf(parent : write %d bytes to pipen, writenum); close(pipe_fd1); sleep(1); exit(0); else perror(fork); exit(1); exit(0);运行结果:$ ./pipechild : read 4096 bytes from pipe, sum = 4096child : read 4096 bytes from pipe, sum = 8192child : read 4096 bytes from pipe, sum
4、 = 12288child : read 4096 bytes from pipe, sum = 16384child : read 4096 bytes from pipe, sum = 20480child : read 4096 bytes from pipe, sum = 24576child : read 4096 bytes from pipe, sum = 28672child : read 4096 bytes from pipe, sum = 32768child : read 4096 bytes from pipe, sum = 36864child : read 409
5、6 bytes from pipe, sum = 40960child : read 4096 bytes from pipe, sum = 45056child : read 4096 bytes from pipe, sum = 49152child : read 4096 bytes from pipe, sum = 53248child : read 4096 bytes from pipe, sum = 57344child : read 4096 bytes from pipe, sum = 61440child : read 4096 bytes from pipe, sum =
6、 65536parent : write 131072 bytes to pipechild : read 4096 bytes from pipe, sum = 69632child : read 4096 bytes from pipe, sum = 73728child : read 4096 bytes from pipe, sum = 77824child : read 4096 bytes from pipe, sum = 81920child : read 4096 bytes from pipe, sum = 86016child : read 4096 bytes from
7、pipe, sum = 90112child : read 4096 bytes from pipe, sum = 94208child : read 4096 bytes from pipe, sum = 98304child : read 4096 bytes from pipe, sum = 102400child : read 4096 bytes from pipe, sum = 106496child : read 4096 bytes from pipe, sum = 110592child : read 4096 bytes from pipe, sum = 114688chi
8、ld : read 4096 bytes from pipe, sum = 118784child : read 4096 bytes from pipe, sum = 122880child : read 4096 bytes from pipe, sum = 126976child : read 4096 bytes from pipe, sum = 131072child : no more bytes to read from pipe$结论:对于阻塞式的pipe,当写入的数据量较大时,并不是以原子性方式写入,而是分多次写入。pipe的缓冲区是65536字节,这个是无法修改的。另外,在FIFO中经常提到的一个PIPE_BUF(Linux : 4096bytes),它仅是保证原子性写入的一个限制,并不是pipe的capacity,相关知识可以参考:pipe(7)