Unix管道实现报错:Ubuntu下调试C程序管道示例遇问题
Fixing Issues with Piping the
summer and bingo Programs Hey there! Let's break down the problems in your current code and get those two programs communicating over a pipe properly, since you're working through System Programming with C and Unix by Adam Hoover.
Key Problems in Your Current Code
- Buffering Gotcha: When you run
summer | bingo,summer's stdout is connected to a pipe (not a terminal), soprintf("#?")gets stuck in stdio's full buffer instead of showing up immediately. Terminal output uses line buffering, but pipes switch to full buffering by default. - Non-Standard
main:void main()isn't compliant with the C standard—stick withint main()and return a status code (like0for success). - Mismatched String Matching: Your
summerprogram outputssum = %d(note the space betweensumand=), but you're checking for"sum=5"inbingo. On top of that,scanf("%s", s)splits input on spaces, so it'll only read"sum"or"="or"5"separately—never the full line. - Incomplete Logic: Your
bingocode cuts off atif ( strcmp(s,"sum=5") == 0 )...—we need to add the actual "bingo" behavior.
Revised Code
summer.c
#include<stdio.h> #include<stdlib.h> int main() { int x, sum = 0; while (1) { printf("#?"); fflush(stdout); // Force output to show immediately, even through a pipe // Handle cases where input isn't a number or EOF is reached if (scanf("%d", &x) != 1) { break; } if (x == 0) { break; } sum += x; printf("sum = %d\n", sum); fflush(stdout); // Make sure the sum is sent to the pipe right away } return 0; }
bingo.c
#include<stdio.h> #include<string.h> #include<stdlib.h> int main() { char line[80]; // Read full lines instead of splitting on spaces while (fgets(line, sizeof(line), stdin) != NULL) { // Remove the trailing newline character that fgets includes line[strcspn(line, "\n")] = '\0'; if (strcmp(line, "sum = 5") == 0) { printf("BINGO! You hit the target sum of 5!\n"); // Optional: Exit once we hit bingo, or keep listening // exit(EXIT_SUCCESS); } // Uncomment below for debugging to see what's being received // printf("Received line: %s\n", line); } return 0; }
How to Compile and Run
- Compile both programs first:
gcc summer.c -o summer gcc bingo.c -o bingo - Run them connected with a pipe:
Now when you enter numbers, once the sum hits 5,./summer | ./bingobingowill shout out its success!
Quick Notes
- The
fflush(stdout)calls are critical here—without them,summer's output gets buffered up andbingowon't see it until the buffer fills up, which breaks the interactive flow. - Using
fgetsinstead ofscanf("%s")ensures we capture the entire line of output fromsummer, including spaces, so the string comparison works as expected. - Adding error handling for
scanfprevents the program from hanging if you enter something that isn't a number.
内容的提问来源于stack exchange,提问作者BlackBrain
相关产品推荐
相关产品推荐

