我正在尝试创建一个程序,使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");
}
Run Code Online (Sandbox Code Playgroud)
现在,我必须在每个孩子身上打印出他是什么孩子,从0开始,所以我在想这个:
printf("This is child #%d\n", getpid() - getppid());
Run Code Online (Sandbox Code Playgroud)
但是我不确定,这总是有效吗?如果在父母创建子系统时操作系统创建另一个进程怎么办?孩子的数量将会停止?最后,如果答案是肯定的,我怎样才能让#n孩子知道他是孩子的数字n?
您可以使用该i变量来判断您所在的孩子,但循环的逻辑是不正确的.它应该是这样的:
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.
}
Run Code Online (Sandbox Code Playgroud)
操作系统不需要按顺序分配进程ID.如果另一个进程正在使用下一个进程,它将在顺序分配方法中跳过,但操作系统可以真正分配一个随机数作为pid,只要它没有被使用.