fork

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

int main(int argc, char *argv)
{
    pid_t pid = fork();
    if(pid < 0){
        perror("fork");
        exit(0);
    }

    if(pid == 0){
        // child process
        int n = 8;
        while(n--){
            printf("child\n");
            sleep(1);
        }
        
        exit(0);
    }

    int n = 3;
    while(n--){ // parent process
        printf("parent\n");
        sleep(1);
    }
    wait(NULL); // 阻塞等待第一个子进程退出,回收资源
    exit(0);

}

原文地址:https://www.cnblogs.com/mathzzz/p/2648675.html