孩子和家长的PID叉(); [英] Child and Parent pid with fork();
问题描述
我试图做一个程序,让9子进程,所以我用叉子只有9倍,如果我们的父亲,像这样的:
I'm trying to make a program which make 9 child process, so I use fork 9 times only if we are the father, like this:
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");
}
现在,我必须打印在每个孩子他是什么样的孩子,从0开始,所以我想这个问题:
Now, I have to print on each children what children he is, starting from 0, so I was thinking about this:
printf("This is child #%d\n", getpid() - getppid());
但是我不知道,这是否总是工作?如果当父创建儿童操作系统创建另一个进程?儿童的人数将停止?
最后,如果答案是肯定的,我怎么能作出这样的#N孩子们知道,他是孩子数n?
推荐答案
您可以使用 I
变量来告诉你是哪个孩子,但你的循环逻辑不正确。它应该是这样的:
You can use the i
variable to tell which child you are in, but the logic of your loop is incorrect. It should go like this:
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的,因为它是在不使用
The operating system is not required to assign process IDs in sequential order. If another process is using the next one, it would be skipped over in a sequential assignment method, but the OS could really assign a random number as the pid as long as it is not in use.
这篇关于孩子和家长的PID叉();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!