Linux下C语言进程与无限循环问题:多进程求和程序死循环
Hey there, let's break down why your C program is getting stuck in an infinite loop after spawning the second process, and fix it up properly to meet your requirements.
The Root Cause
The main issue comes down to how fork() works: when you call fork(), the child process gets an exact copy of the parent's entire address space—including your loop counter variable. If you don't explicitly exit the child process right after it does its job, it will keep running the same loop as the parent, spawning even more child processes endlessly. That's exactly what's causing your infinite loop.
Fixed Complete Code
Here's a working version that creates n processes, generates unique random numbers per process, and calculates their total sum:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> #include <time.h> int main(int argc, char *argv[]) { // Validate command line arguments if (argc != 2) { fprintf(stderr, "Usage: %s <number_of_processes>\n", argv[0]); exit(EXIT_FAILURE); } int n = atoi(argv[1]); if (n <= 0) { fprintf(stderr, "Please enter a positive integer for n.\n"); exit(EXIT_FAILURE); } // Seed random number generator uniquely for each process srand(time(NULL) ^ getpid()); int total_sum = 0; for (int i = 0; i < n; i++) { pid_t pid = fork(); if (pid == -1) { perror("Failed to create process"); exit(EXIT_FAILURE); } else if (pid == 0) { // Child process logic: generate and print random number int random_num = (rand() % 201) - 100; // Range: -100 to 100 printf("Child %d (PID: %d) generated: %d\n", i+1, getpid(), random_num); exit(random_num); // Exit with the random number as status code } // Parent process continues to next iteration to create more children } // Parent waits for all children to finish and collects their values for (int i = 0; i < n; i++) { int exit_status; pid_t completed_pid = wait(&exit_status); if (completed_pid == -1) { perror("Failed to wait for child process"); exit(EXIT_FAILURE); } if (WIFEXITED(exit_status)) { int child_value = WEXITSTATUS(exit_status); // Convert back to negative value (since exit status is 0-255 unsigned) if (child_value > 127) { child_value -= 256; } total_sum += child_value; } } printf("Total sum of all random numbers: %d\n", total_sum); return EXIT_SUCCESS; }
Key Fixes & Explanations
- Stopping the Infinite Loop: In the child process block, we call
exit(random_num)immediately after generating and printing the random number. This ensures the child doesn't continue executing the parent's loop, preventing endless process spawning. - Unique Random Numbers: Using
srand(time(NULL) ^ getpid())instead of justsrand(time(NULL))ensures each process gets a unique seed (since every process has a unique PID). Without this, all children would inherit the same seed from the parent and generate identical random numbers. - Collecting Child Values: We use the child's exit status code to pass the random number back to the parent. Since exit statuses are unsigned 8-bit values (0-255), we convert values greater than 127 back to their original negative form (e.g., -100 becomes 156 in the exit status, so 156-256 = -100).
- Waiting for Children: The parent uses a second loop with
wait()to wait for every child to finish. This avoids zombie processes and ensures we collect every random number to calculate the total sum.
Quick Debug Tip
If you ever run into similar process issues again, add debug prints inside the loop showing the current process PID and loop counter value. You'll immediately see if child processes are continuing the loop instead of exiting.
内容的提问来源于stack exchange,提问作者Neil Shah




