C半双工管道
程序员文章站
2022-05-09 17:01:03
...
父进程不断发送消息到子进程,子进程收到消息后发送回应;
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "common.h" int main(void) { int subPid = 0; int fd1[2] = {0}, fd2[2] = {0}; char readBuffer[BUFFER_SIZE]; char writeBuffer[BUFFER_SIZE]; int readLength = 0; int writeLength = 0; int ret = 0; ret = pipe(fd1); if (-1 == ret) { perror(""); return -1; } ret = pipe(fd2); if (-1 == ret) { perror(""); return -1; } subPid = fork(); if (0 == subPid) { close(fd1[1]); close(fd2[0]); while (true) { readLength = read(fd1[0], readBuffer, BUFFER_SIZE); if (0 > readLength) { perror(""); return -1; } else { printf("CHILD: Received message \"%s\"!\n", readBuffer); strcpy(writeBuffer, "Replay from child!"); write(fd2[1], writeBuffer, strlen(writeBuffer)); } } } else { close(fd1[0]); close(fd2[1]); int sendCount = 0; while (true) { sprintf(writeBuffer, "Message from server (total: %d) !", ++sendCount); write(fd1[1], writeBuffer, strlen(writeBuffer)); readLength = read(fd2[0], readBuffer, BUFFER_SIZE); if (0 > readLength) { perror(""); return -1; } printf("PARENT: Received replay from child \"%s\"!\n", readBuffer); usleep(1000000); } } return 1; }
上一篇: mysql日期函数总结
下一篇: mkfifo 和nc
推荐阅读
-
安装Oracle OEM 12c的过程(简单版)
-
spring 下配置 dbcp,c3p0,proxool 等数据源连接池
-
基于SQLite数据库的C语言编程
-
用C# + SqlServer2005 实现的treeview动态树形菜单
-
spring 下配置 dbcp,c3p0,proxool 等数据源连接池
-
【转载】C#通过Contains方法判断DataTable中是否存在某个列名
-
【转载】C#通过遍历DataTable的列获取所有列名
-
雷军官宣红米8/8A将搭载Type-C接口:正反都能插
-
【转载】C#的Merge方法合并两个DataTable对象的数据
-
【转载】C#如何往DataTable中新增一个数据列