Pipe 简单的例子

本文详细介绍了管道通信的概念、使用方法以及在进程间数据传递的应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如下是Pipe的一个简单的例子。管道的通信是单项的。只能一端写,一端读。管道通信只能在有共同祖先的两个进程之间。在两个进程中,进行数据传送。pipe(fd)创建管道,fd【0】作为read端,fd【1】作为写入端。当fd[1]不存在的时候,认为已经读到结尾,read返回0.如果fd[1]存在,写入数据后,将写入端关闭,但是数据一直存在,直到读出。数据总是写在管道的尾部,而读的时候,则是从头部开始读取。#include #include #include #include #include int fd[2]; int main() {pid_t pid; char buffer[PIPE_BUF]; memset(buffer, 0, PIPE_BUF); if(pipe(fd) < 0) {printf("Failed to create a pipe!!\n");return 0;}if (0 == (pid = fork())) {printf("sub pid = %d\n", pid);close(fd[1]);// close the write pipesleep(1);// has time for write if (read(fd[0], buffer, 32) > 0){ printf("receive data from server, %s\n!!",buffer);}close(fd[0]);} else {printf("master pid = %d\n", pid);close(fd[0]);// close the write pipeif (-1 != write(fd[1], "Hello World", strlen("Hello World"))) { // write data to pipeprintf("send data to cline hello world!!!\n");}close(fd[1]);// close writewaitpid(pid, NULL, 0);}return 1;}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值