管道 两个子进程通信问题
刚开始学c语言有个问题想请教大家
通过管道建立两个子进程,子进程1向子进程2输入一个"Hello" 子进程2向子进程1回复“hELLO” 这个例子怎么实现啊
#include<unistd.h> #include<stdio.h> #include<string.h> #include<sys/types.h> #include<stdlib.h> #include<sys/wait.h> void read_pipe(int fd) { char message[100]; read(fd, message, 100); printf("read pipe message:%s", message); } void write_pipe(int fd) { char *message = "Hello\n"; write(fd, message, strlen(message) + 1); } int main() { int fd[2]; pid_t pid; int stat_val; if (pipe(fd)) { printf("create pipe failed!\n"); } pid = fork(); switch (pid) { case -1: printf("fork error!\n"); break; case 0: close(fd[1]); read_pipe(fd[0]); break; default: close(fd[0]); write_pipe(fd[1]); wait(&stat_val); break; } return 0; }
#include<unistd.h> #include<stdio.h> #include<string.h> #include<sys/types.h> #include<stdlib.h> #include<sys/wait.h> int main() { int fd1[2]; int fd2[2]; pid_t pid; int stat_val; char strMsg[20]; char strMsgP2C[20]="Hello"; char strMsgC2P[20]="hELLO"; if (pipe(fd1)) { printf("create pipe1 failed!\n"); } if (pipe(fd2)) { printf("create pipe1 failed!\n"); } pid = fork(); switch (pid) { case -1: // error printf("fork error!\n"); break; case 0: // Child Process close(fd1[1]); close(fd2[0]); memset(strMsg,0,sizeof(strMsg)); read(fd1[0],strMsg,sizeof(strMsg)); printf("Child Process Get MSG: %s\n",strMsg); write(fd2[1],strMsgC2P,strlen(strMsgC2P)); break; default: // Parent Process close(fd1[0]); close(fd2[1]); write(fd1[1],strMsgP2C,strlen(strMsgP2C)); memset(strMsg,0,sizeof(strMsg)); read(fd2[0],strMsg,sizeof(strMsg)); printf("Parent Process Get MSG: %s\n",strMsg); wait(&stat_val); break; } return 0; }