gpt4 book ai didi

c - C中的fork过程

转载 作者:行者123 更新时间:2023-11-30 19:04:06 26 4
gpt4 key购买 nike

我在系统编程过程中有以下代码:

/* La fonction create_process duplique le processus appelant et retourne
le PID du processus fils ainsi créé */
pid_t create_process(void)
{
/* On crée une nouvelle valeur de type pid_t */
pid_t pid;

/* On fork() tant que l'erreur est EAGAIN */
do {
pid = fork();
} while ((pid == -1) && (errno == EAGAIN));

/* On retourne le PID du processus ainsi créé */
return pid;
}

/* La fonction child_process effectue les actions du processus fils */
void child_process(void)
{
printf(" We are in the son's process !\n"
" son's pid is est %d.\n"
" son's PPID is %d.\n", (int) getpid(), (int) getppid());
}

/* La fonction father_process effectue les actions du processus père */
void father_process(int child_pid)
{
printf(" We are in the father process !\n"
" son's PID is %d.\n"
" father's PID is %d.\n", (int) child_pid, (int) getpid());
}

int main(void)
{
pid_t pid = create_process();

switch (pid) {
/* Si on a une erreur irrémédiable (ENOMEM dans notre cas) */
case -1:
perror("fork");
return EXIT_FAILURE;
break;
/* Si on est dans le fils */
case 0:
child_process();
break;
/* Si on est dans le père */
default:
father_process(pid);
break;
}

return EXIT_SUCCESS;
}

该函数的输出是:

我们正在父亲的进程中! 儿子的PID是6246。 父亲的PID是6245。 我们正在儿子的进程中! 儿子的PID是6246。 儿子的 PPID 为 1。

我不明白为什么这段代码会产生这样的输出:函数 create_process 从父进程派生一个新进程。因此,在父进程中,函数 create_process 返回 child_process pid,我理解第一部分:

We are in the father's process!
son's PID is 6246.
father's PID is 6245.

然后我猜测 child_process 正在执行并且 create_process 函数返回 0,因为我们现在处于 child_process 中并且我也理解以下输出:

We are in the son's process!
son's PID is 6246.
son's PPID is 1.

但我不明白为什么执行之后停止...我们仍在 fork 子进程,对吗?所以我觉得它应该继续创建新的流程和打印:

We are in the son's process !
son's PID is OTHER.
son's PPID is 6246.

有人可以向我解释一下为什么这段代码不继续创建进程吗

最佳答案

do {
pid = fork();
} while ((pid == -1) && (errno == EAGAIN));

假设对fork的调用成功,它只会被调用一次。所以只创建了一个新进程。然后子进程调用child_process,父进程调用father_process。之后,它们都返回到 main 函数,在该函数中突破 switch 语句并从 main 返回。

关于c - C中的fork过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52858795/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com