[英]Child and Parent pid with fork();
我正在嘗試制作一個使9個子進程通過的程序,因此僅當我們是父親時,我才使用9次fork,如下所示:
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開始在每個孩子上打印他是什么孩子,所以我在考慮以下問題:
printf("This is child #%d\n", getpid() - getppid());
但是我不確定,這是否始終有效?,如果在父級創建子級操作系統的同時創建另一個進程,該怎么辦?子級數將中斷? 最后,如果答案是肯定的,我該如何使#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.
}
不需要操作系統按順序分配進程ID。 如果另一個進程正在使用下一個進程,則將以順序分配方法跳過該進程,但是OS可以真正分配一個隨機數作為pid(只要不使用它)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.