📜  使用fork()创建多个进程(1)

📅  最后修改于: 2023-12-03 14:49:48.203000             🧑  作者: Mango

使用fork()创建多个进程

在Linux系统中,可以使用fork()系统调用来创建一个子进程,让这个子进程与父进程运行相同的代码。在子进程中,可以使用getpid()函数获取子进程的进程ID(PID),而在父进程中,可以使用wait()函数等待子进程的结束。

代码示例

下面是一个示例程序,使用fork()调用创建两个子进程并在每个子进程中分别输出一句话。在父进程中,使用wait()函数等待子进程结束后输出"Child process has finished."。

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

int main(void)
{
    /* Create first child process */
    pid_t pid1 = fork();

    if (pid1 == 0)
    {
        /* This is the first child process */
        printf("This is the first child process. PID: %d\n", getpid());
        exit(0);
    }
    else if (pid1 < 0)
    {
        printf("Error creating first child process.\n");
        return -1;
    }

    /* Create second child process */
    pid_t pid2 = fork();

    if (pid2 == 0)
    {
        /* This is the second child process */
        printf("This is the second child process. PID: %d\n", getpid());
        exit(0);
    }
    else if (pid2 < 0)
    {
        printf("Error creating second child process.\n");
        return -1;
    }

    /* Wait for child processes to finish */
    wait(NULL);
    wait(NULL);

    printf("Child process has finished.\n");

    return 0;
}

以上代码先创建了一个子进程pid1,并分别判断是否创建成功。在子进程中,输出一句话并使用exit()函数退出。然后再创建第二个子进程pid2,并再次判断是否创建成功。同样,在第二个子进程中输出一句话并使用exit()函数退出。最后在父进程中使用wait()函数等待两个子进程结束后输出一句话。

运行结果

运行以上代码的输出结果如下:

This is the first child process. PID: 2078
This is the second child process. PID: 2079
Child process has finished.

首先输出了两个子进程中的内容,然后输出父进程的内容。可以看到,两个子进程的PID分别为2078和2079。

总结

使用fork()系统调用可以很容易地创建多个子进程,每个子进程都与父进程运行相同的代码。在子进程中可以使用getpid()函数获取PID,而在父进程中可以使用wait()函数等待子进程结束。