#include <stdio.h> #include <stdlib.h> #include <unistd.h>

int main() { pid_t pid1, pid2;

pid1 = fork(); // 创建第一个子进程
if (pid1 < 0) { // 创建失败
    printf('Error: fork() failed.\n');
    exit(1);
} else if (pid1 == 0) { // 子进程1
    printf('E');
    fflush(stdout); // 刷新缓冲区,确保输出被立即输出
    exit(0);
} else { // 父进程
    pid2 = fork(); // 创建第二个子进程
    if (pid2 < 0) { // 创建失败
        printf('Error: fork() failed.\n');
        exit(1);
    } else if (pid2 == 0) { // 子进程2
        printf('F');
        fflush(stdout); // 刷新缓冲区,确保输出被立即输出
        exit(0);
    } else { // 父进程
        wait(NULL); // 等待子进程1结束
        wait(NULL); // 等待子进程2结束
        printf('\n'); // 输出换行符,确保输出的内容在新的一行
    }
}

return 0;

}

C语言实现两个子进程分别输出'E'和'F'

原文地址: https://www.cveoy.top/t/topic/jJbu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录