为了账号安全,请及时绑定邮箱和手机立即绑定

作业社区

探索学习新天地,共享知识资源!

0 提交作业
0 布置作业
0 满分作业
得分 100
学习任务

慕九州9493288 的学生作业:

一、代码 #include #include #include #include #include #include #define BUF_SIZE 1024 /** * 1、创建一个子进程 * 2、子进程负责循环从管道读取数据并输出 * 3、父进程从键盘读取数据后,负责向管道写入数据 * 4、输入“quit”字符串时退出 */ int main(void) { int pipefd[2] = {0}; int ret; pid_t cpid; ret = pipe(pipefd); if (ret == -1) { perror("[ERROR] pipe():"); exit(EXIT_FAILURE); } cpid = fork(); if (cpid == -1) { perror("[ERROR] fork():"); exit(EXIT_FAILURE); } else if (cpid == 0) { //子进程 char buf[BUF_SIZE] = {0}; ssize_t rbytes; close(pipefd[1]); while (1) { memset(buf, 0, sizeof(buf)); //清空缓存区 rbytes = read(pipefd[0], buf, sizeof(buf) - 1); if (rbytes == -1) { perror("[ERROR] read():"); close(pipefd[0]); exit(EXIT_FAILURE); } else if (rbytes == 0) { printf("\n[CHILD] 父进程已退出,子进程退出\n"); break; } else { buf[rbytes] = '\0'; printf("\n[CHILD] 收到数据:%s\n", buf); fflush(stdout); } } close(pipefd[0]); //子进程关闭读端 exit(EXIT_SUCCESS); } else if (cpid > 0) { char buf[BUF_SIZE] = {0}; ssize_t wbytes; char *ret; close(pipefd[0]); while (1) { memset(buf, 0, sizeof(buf)); //清空缓存区 printf("\n[PARENT] 请输入内容(输入quit退出):"); fflush(stdout); ret = fgets(buf, sizeof(buf), stdin); if (ret == NULL) { perror("[ERROR] fgets():"); break; } buf[strcspn(buf, "\n")] = '\0'; //替换换行符 if (strncmp(buf, "quit", 4) == 0) { printf("[PARENT] Exit!\n"); break; } wbytes = write(pipefd[1], buf, strlen(buf)); if (wbytes == -1) { perror("[ERROR] write():"); break; } printf("[PARENT] 已写入 %zd 字节数据\n", wbytes); fflush(stdout); usleep(10000); //防止子进程未读取到数据 } close(pipefd[1]); //父进程关闭写端 wait(NULL); printf("[PARENT] 子进程已退出,父进程退出\n"); } return EXIT_SUCCESS; } 二、结果 linux@DESKTOP-4M60T5C:~/homework/2026/0209$ gcc hw_pipe.c linux@DESKTOP-4M60T5C:~/homework/2026/0209$ ./a.out [PARENT] 请输入内容(输入quit退出):hello pipe! [PARENT] 已写入 11 字节数据 [CHILD] 收到数据:hello pipe! [PARENT] 请输入内容(输入quit退出):quit [PARENT] Exit! [CHILD] 父进程已退出,子进程退出 [PARENT] 子进程已退出,父进程退出

微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号