如何在C/Unix中用fork+exec实现无fork炸弹的持续任务执行?
Question
I have this C code which I believe is a fork bomb:
char *args = "echo hello world"; while(1) { pid_t pid = fork(); if(pid == 0) { execlp("sh", "sh", "-c", args, (char *)NULL); perror("sh"); return(1); } else if(pid == -1) { perror("fork"); return(1); } }
I want to know if it's possible to keep using fork() to continuously output "hello world" to stdout without triggering a fork bomb—specifically, by waiting for each child process to terminate before starting a new one.
Answer
Absolutely, this is totally achievable! The original code acts as a fork bomb because it spawns new child processes without waiting for existing ones to finish, leading to an exponential explosion of active processes that quickly overwhelms the system's resources. By adding a step where the parent process waits for the child to exit before looping again, we eliminate this risk entirely.
Here's a modified version of your code that works safely:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h> int main() { char *args = "echo hello world"; while(1) { pid_t pid = fork(); if(pid == 0) { // Child process: run the echo command execlp("sh", "sh", "-c", args, (char *)NULL); perror("sh"); // Only runs if execlp fails exit(1); } else if(pid == -1) { perror("fork"); return 1; } else { // Parent process: wait for the child to terminate before continuing waitpid(pid, NULL, 0); // Alternatively, use wait(NULL) for simplicity } } return 0; }
Key Details:
waitpid(pid, NULL, 0): This tells the parent process to pause execution until the specific child process (identified bypid) has exited. If you don't need to track the exact child,wait(NULL)works just as well here—it waits for any child process to finish.- No Process Pileup: With this wait step, each loop iteration creates exactly one child process, waits for it to print "hello world" and exit, then creates the next child. There's never more than one active child process at a time, so no fork bomb scenario.
- Proper Includes: I added necessary headers (
<sys/wait.h>for wait functions,<stdlib.h>forexit()) that were missing in the original code to ensure it compiles and runs correctly.
内容的提问来源于stack exchange,提问作者e t

