实现AB进程对话。
A进程发送一句话后,B进程接收到打印。然后B进程发送一句话,A进程接收后打印
重复上述步骤。直到AB接收或者发送完quit后,结束AB进程
提示用两根管道
附加题:实现AB进程随时通话
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <sys/stat.h> #include <string.h> #include <errno.h> int main() { int fd_ab, fd_ba; char buffer[1024]; //创建管道 if(!mkfifo("./fifo_ab",0775)){ //17号错误是指文件以存在,但我们只是想确保文件存在,并不是单纯为了创建文件 if(errno!=17){ perror("mkfifo"); return -1; } } if(!mkfifo("./fifo_ba",0775)){ perror("mkfifo"); return -1; } pid_t pid = fork(); if (pid > 0) { fd_ab = open("fifo_ab", O_WRONLY); fd_ba = open("fifo_ba", O_RDONLY); while (1) { printf("A->B:"); fgets(buffer, sizeof(buffer), stdin); write(fd_ab, buffer, strlen(buffer) + 1); if (strcmp(buffer, "quit\n") == 0) { puts("A进程退出"); break; } read(fd_ba, buffer, sizeof(buffer)); printf("A<-B:%s", buffer); if (strcmp(buffer, "quit\n") == 0) { break; } } close(fd_ab); close(fd_ba); } else { fd_ab = open("fifo_ab", O_RDONLY); fd_ba = open("fifo_ba", O_WRONLY); while (1) { read(fd_ab, buffer, sizeof(buffer)); printf("B<-A:%s", buffer); if (strcmp(buffer, "quit\n") == 0) { puts("B进程退出"); break; } printf("B->A:"); fgets(buffer, sizeof(buffer), stdin); write(fd_ba, buffer, strlen(buffer) + 1); if (strcmp(buffer, "quit\n") == 0) { break; } } close(fd_ab); close(fd_ba); } return 0; }
。(提示:多进程或者多线程)
0614作业
最新推荐文章于 2024-08-24 22:01:16 发布