使用Pipes的三进程中第三个进程无法运行的排查求助
多进程管道阻塞问题:助教提供的骨架代码是否存在错误?
我正在完成计算机架构课程的作业,需要用C语言实现三个基于管道通信的进程,但第三个进程始终无法正常运行。助教提供了骨架代码,我参加了额外辅导也没解决,其他同学也反馈这个骨架代码可能有问题,但助教没有明确回应。
目前代码能把正确结果打印到屏幕,但没办法写入output.txt文件,而且会卡在第三个进程。我们的学习重点是管道(Pipes)和延迟,不是C语言本身,我试过加sleep()、wait(NULL)等方法都没用。
我的核心疑问:
- 这份骨架代码确实存在错误吗?
- 能否修复代码,帮我理解管道相关的核心概念?
骨架代码及我的修改说明
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <ctype.h> #define READ_END 0 #define WRITE_END 1 int main(int argc, char* argv[]) { // declare pipes int fd1[2], fd2[2]; pid_t pid; if (pipe(fd1) == -1 || pipe(fd2) == -1) { fprintf(stderr, "Pipe failed"); return 1; } pid = fork(); if (pid < 0) { fprintf(stderr, "Fork Failed"); return 1; } if (pid > 0) { // Parent process close(fd1[READ_END]); close(fd2[WRITE_END]); FILE* fp = fopen("input.txt", "r"); // //FILE* fp2 = fopen("output.txt", "w"); // if (fp == NULL) { fprintf(stderr, "Failed to open file\n"); exit(1); } char line[BUFSIZ]; while (fgets(line, BUFSIZ, fp)) { write(fd1[WRITE_END], line, strlen(line)); memset(line, 0, BUFSIZ); read(fd2[READ_END], line, BUFSIZ); printf("%s", line); //fprintf(fp2, "%s", line); this isn't allowed } fclose(fp); //fclose(fp2); close(fd1[WRITE_END]); close(fd2[READ_END]); } else { // Child process pid = fork(); if (pid > 0) { // Second process close(fd1[WRITE_END]); close(fd2[READ_END]); char line[BUFSIZ]; while (read(fd1[READ_END], line, BUFSIZ)) // 注释1*:我编写的进程逻辑,能正常运行并打印到屏幕 { for (int i = 0; i < strlen(line); i++) { // Change lower to upper and upper to lower cases // write code here if(isupper(line[i])) { line[i]=tolower(line[i]); } else if(islower(line[i])) { line[i]=toupper(line[i]); } } // 以下是骨架代码 write(fd2[WRITE_END], line, strlen(line)); memset(line, 0, BUFSIZ); } close(fd1[READ_END]); close(fd2[WRITE_END]); } else { // Third process // 注释2*:我自行编写的代码,也是卡住的位置 // Close unused pipes //write code here close(fd1[READ_END]); close(fd2[WRITE_END]); close(fd1[WRITE_END]); // 剩下的是骨架代码,但我需要修改while循环内的代码来写入output.txt FILE* fp = fopen("output.txt", "w"); char line[BUFSIZ]; // 下面的代码被注释了,因为会卡在这个循环里 /* while (read(fd2[READ_END], line, BUFSIZ)) { // prints to the output.txt file // write code here fprintf(fp,"%s", line); } */ fclose(fp); close(fd2[READ_END]); } } return 0; }
我尝试过的解决方法
- 在第二个进程的循环首尾添加
sleep(2)、sleep(3) - 在第三个进程设置相反时长的
sleep,或者仅在第三个进程开头加sleep(10) - 在多处添加
wait(NULL) - 在第三个进程的循环前后加打印语句,循环前的语句有时会在代码看似结束后才输出
- 打印
read(fd2[READ_END], line, BUFSIZ)的返回值,有时是0有时是数字,原因不明 - 打印
BUFSIZ的值,但结果无法理解
内容的提问来源于stack exchange,提问作者Samantha Garcia
相关产品推荐
相关产品推荐

