C半双工管道
父进程不断发送消息到子进程,子进程收到消息后发送回应;#include <unistd.h>#include <stdlib.h>#include <stdio.h>#include <string.h>#include "common.h"int main(void){int subPid = 0;int fd1 = {0}, fd2 = {0};char readBuffer;char writeBuffer;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);close(fd2);while (true){readLength = read(fd1, readBuffer, BUFFER_SIZE);if (0 > readLength){perror("");return -1;}else{printf("CHILD: Received message \"%s\"!\n", readBuffer);strcpy(writeBuffer, "Replay from child!");write(fd2, writeBuffer, strlen(writeBuffer));}}}else{close(fd1);close(fd2);int sendCount = 0;while (true){sprintf(writeBuffer, "Message from server (total: %d) !", ++sendCount);write(fd1, writeBuffer, strlen(writeBuffer));readLength = read(fd2, readBuffer, BUFFER_SIZE);if (0 > readLength){perror("");return -1;}printf("PARENT: Received replay from child \"%s\"!\n", readBuffer);usleep(1000000);}}return 1;}
页:
[1]