gpt4 book ai didi

c++ - 使用 fork() 的子和父 pid;

转载 作者:太空宇宙 更新时间:2023-11-04 05:56:39 25 4
gpt4 key购买 nike

我正在尝试制作一个包含 9 个子进程的程序,所以只有当我们是父进程时我才使用 fork 9 次,如下所示:

for (int i = 0; i < 9; i++) {   // Creo 9 hijos.
if (child_pid > 0) {
child_pid = fork();
childs[i] = child_pid;
}
if (child_pid < 0)
printf("Error...\n");
}

现在,我必须在每个 child 上打印他是什么 child ,从 0 开始,所以我在考虑这个:

printf("This is child #%d\n", getpid() - getppid());

但我不确定,这是否总是有效?如果父进程正在创建子进程时操作系统创建了另一个进程怎么办?子进程的数量会停止吗?。最后,如果答案是肯定的,我怎样才能让#n 个 child 知道他是第 n 个 child ?。

最佳答案

您可以使用 i 变量来判断您在哪个 child 中,但是您的循环逻辑不正确。它应该是这样的:

for (int i = 0; i < 9; ++i) {
child_pid = fork();

if (child_pid == 0) {
// We are the child. The value of the i variable will tell us which one.
// If i == 0 we are the first child, i == 1 and we are the second, and so on.
printf("We are child #%d\n", i);
exit(EXIT_SUCCESS);
}

if (child_pid < 0) {
// Forking failed.
perror("fork()");
exit(EXIT_FAILURE);
}

// Otherwise we are the parent and forking was successful; continue the loop.
}

操作系统不需要按顺序分配进程 ID。如果另一个进程正在使用下一个进程,它将在顺序分配方法中被跳过,但操作系统实际上可以分配一个随机数作为 pid,只要它不在使用中。

关于c++ - 使用 fork() 的子和父 pid;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26310824/

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