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

C语言:修改程序实现父进程创建3个子进程并等待其终止

How to Create 3 Child Processes (Parent Only) and Wait for Them to Finish

Hey there! Let's walk through how to write this code exactly how you need it—since you're new to C process management, I'll break every part down so it makes sense.

First, here's the complete, working code that matches your requirements:

#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>

// Replace this with your actual CPU() function implementation
void CPU() {
    printf("Child process %d is running the CPU() function\n", getpid());
    // Example: Simple loop to simulate CPU work (adjust as needed)
    for (long j = 0; j < 100000000; j++);
}

int main(void) {
    int i;

    // Parent creates 3 child processes
    for (i = 0; i < 3; i++) {
        pid_t child_pid = fork(); // Use pid_t for proper process ID storage

        if (child_pid == -1) {
            // Handle fork failure (rare, but good practice to check)
            perror("Failed to create child process");
            return 1;
        } else if (child_pid == 0) {
            // This is the CHILD process
            CPU(); // Call your CPU function
            printf("Child process %d is exiting\n", getpid());
            return 0; // Critical: Exit child so it doesn't create more processes
        } else {
            // This is the PARENT process
            printf("Parent %d created child process %d\n", getpid(), child_pid);
        }
    }

    // Parent waits for ALL 3 children to terminate
    printf("\nParent %d is waiting for all children to finish...\n", getpid());
    for (i = 0; i < 3; i++) {
        wait(NULL); // Pause until one child exits; call 3x for all children
        printf("One child process has terminated\n");
    }

    printf("All children exited. Parent %d is done!\n", getpid());
    return 0;
}

Key Details for You (Since You're New):

  • Required Headers:

    • <unistd.h>: Gives us fork() (to create processes) and getpid() (to get process ID).
    • <sys/wait.h>: Gives us wait(NULL) (to wait for child processes).
    • <stdio.h>: For printing messages.
  • Why return 0 in the child?
    If we didn't exit the child process immediately after calling CPU(), it would continue running the parent's loop code—and start creating its own child processes. That would result in way more than 3 children, which isn't what you want. This line ensures each child only does its job and exits.

  • How wait(NULL) works:
    When the parent calls wait(NULL), it pauses execution until any one of its child processes finishes. By calling it 3 times, we guarantee the parent waits for all 3 children to terminate before moving on.

  • pid_t instead of int:
    This is a standard type for storing process IDs (it's defined by the system to be the right size for your OS). Using it is more规范 (and safer) than just using int.

Testing the Code:

When you compile and run it, you'll see output like this (process IDs will vary):

Parent 1234 created child process 1235
Parent 1234 created child process 1236
Parent 1234 created child process 1237

Parent 1234 is waiting for all children to finish...
Child process 1235 is running the CPU() function
Child process 1235 is exiting
One child process has terminated
Child process 1236 is running the CPU() function
Child process 1236 is exiting
One child process has terminated
Child process 1237 is running the CPU() function
Child process 1237 is exiting
One child process has terminated
All children exited. Parent 1234 is done!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:47:21