当前位置: 首页 > news >正文

Linux pipe()系统调用示例

Linux系统调用pipe函数,创建一个pipe,通过传入的fd数组返回pipe的读、写两端。
其中fd[ 0 ]用于读,fd[ 1 ]用于写。
一个pipe是单向数据传输的,不用用于父子进程双向读写。创建2个pipe实现父子进程间的双线读写。

#include <unistd.h>
#include <stdio.h>
#include <wait.h>int main() {int fds1[2];int fds2[2];// fds[0]用于读,fd[1]用于写// 这里创建2个pipepipe(fds1);pipe(fds2);printf("fds1: %d, %d\n", fds1[0], fds1[1]);printf("fds2: %d, %d\n", fds2[0], fds2[1]);// 创建子进程pid_t pid = fork();if (pid > 0) {// 父进程// 关闭2个pipe中不需要的文件描述符close(fds1[0]);close(fds2[1]);printf("parent: %d: parent process (child: %d)\n", getpid(), pid);char s[128];sprintf(s, "from parent(%d), to child(%d)", getpid(), pid);write(fds1[1], s, sizeof(s));char buf2[80];read(fds2[0], buf2, sizeof(buf2));printf("parent: receive: %s\n", buf2);close(fds1[1]);close(fds2[0]);} else if(pid == 0) {// 子进程// 关闭2个pipe中不需要的文件描述符close(fds1[1]);close(fds2[0]);printf("child: %d: child process, parent(%d)\n", getpid(), getppid());char buf1[80];read(fds1[0], buf1, sizeof(buf1));printf("child: receive: %s\n", buf1);char s[128];sprintf(s, "to parent(%d), from child(%d)", getppid(), getpid());write(fds2[1], s, sizeof(s) );close(fds1[0]);close(fds2[1]);}waitpid(pid, NULL, 0);return 0;
}
http://www.lryc.cn/news/222547.html

相关文章:

  • 音频中的采样率和比特率
  • Python常用脚本
  • Redis5 分布式系统之主从模式
  • 【黑马程序员】Maven 进阶
  • 231108 C语言memset当第三个参数为0,即设置个数为零也不报错
  • HMM与LTP词性标注之马尔科夫模型(HMM原理剖析)
  • Python自动化测试selenium指定截图文件名方法
  • Linux 实现文件后半部分的复制
  • 阿里开源中间件一览
  • Ubuntu20.04下Salome_meca 2022软件安装(支持GPU加速)
  • uniapp:打包ios配置隐私协议框
  • JS逆向爬虫---请求参数加密③【比特币交易爬虫】
  • 云计算:未来科技的超级英雄
  • 【Node.js入门】1.3 开始开发Node.js应用程序
  • ansible-playbook之file模块
  • Vue路由介绍及使用
  • 案例 - 拖拽上传文件
  • github 上传代码报错 fatal: Authentication failed for ‘xxxxxx‘
  • Linux虚拟网络设备之bridge
  • 最后一个大更新!Win11 2023正式发布:Copilot终于来了
  • pandas教程:Reading and Writing Data in Text Format (以文本格式读取和写入数据)
  • 软考高级系统架构设计师系列之:软考高级系统架构设计师论文专题
  • 目标检测中的评价指标
  • 【AI编程】ai编程插件汇总iFlyCode、codegeex
  • 算法通关村第八关|黄金挑战|二叉树的最近公共祖先
  • 亚马逊云科技产品测评』活动征文|通过使用Amazon Neptune来预测电影类型初体验
  • 【获奖论文】2023年数学建模国赛优秀获奖论文
  • 美团三年,总结的10条血泪教训
  • 【CSP认证考试】202309-1:坐标变换(其一)100分解题思路+代码
  • 剩余参数和展开运算符的区别