You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C/Unix中用fork+exec实现无fork炸弹的持续任务执行?

Can we continuously output "hello world" via fork without triggering a fork bomb (waiting for child process to exit first)?

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 by pid) 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> for exit()) that were missing in the original code to ensure it compiles and runs correctly.

内容的提问来源于stack exchange,提问作者e t

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 12:07:55