六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 40|回复: 0

C半双工管道

[复制链接]

升级  27.33%

21

主题

21

主题

21

主题

秀才

Rank: 2

积分
91
 楼主| 发表于 2013-1-26 12:29:40 | 显示全部楼层 |阅读模式
父进程不断发送消息到子进程,子进程收到消息后发送回应;
 
#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;}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表