我想知道是否有辦法暫停進程,但繼續程序。如何暫停進程並繼續程序?
但是,當我打P4
它結束,模具,然後P2創建P5。然後P2死亡和P1創建P3,同樣的事情發生在那裏。
我需要在進程開始死亡之前創建整個'樹'。
不能使用wait
或waitpid()
,因爲它只是針對它的兒子。
有沒有一種方法來暫停P4,並繼續從它的父親嗎?
如果我不能如何實現我的目標?
我目前的代碼:它創建順序如下:
P1 - > P2 - > P4 - > P4模頭 - > P5 - > P5模頭 - > P2模頭 - > P3 - > P6 - > P6模頭 - > P7 - > P7模頭 - > P3模頭 - > P1 DIES
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <time.h>
int main(){
clock_t t;
double time_taken;
t = clock();
int status;
pid_t idProcesso, pai;
printf("P1 created: %d\n", getpid());
idProcesso = fork();
switch(idProcesso)
{
case -1: exit(1);
case 0: //P2
printf("P2 created: %d - son of P1: %d\n", getpid(), getppid());
idProcesso = fork();
switch(idProcesso)
{
case -1: exit(1);
case 0: //P4
printf("P4 created: %d - son of P2: %d\n", getpid(), getppid());
sleep(1);
break;
default://P2
idProcesso = fork();
switch(idProcesso)
{
case -1: exit(1);
case 0://P5
printf("P5 created: %d - son of P2: %d\n", getpid(), getppid());
break;
default://P2
sleep(1);
break;
}
break;
}
break;
default:
idProcesso = fork();
switch(idProcesso)
{
case -1: exit(1);
case 0://P3
printf("P3 created: %d - son of P1: %d\n", getpid(), getppid());
idProcesso = fork();
switch(idProcesso)
{
case -1: exit(1);
case 0://P6
printf("P6 created: %d - son of P3: %d\n", getpid(), getppid());
sleep(1);
break;
default://P3
idProcesso = fork();
switch(idProcesso)
{
case -1: exit(1);
case 0://P7
printf("P7 created: %d - son of P3: %d\n", getpid(), getppid());
break;
default://P3
break;
}
sleep(1);
break;
}
break;
default:
sleep(4);
break;
}
break;
}
printf("Process id: %d terminated\n", getpid());
exit(0);
}
在最近的linux上你可以重新父進程:http://stackoverflow.com/questions/6476452/process-re-parenting-controlling-who-is-the-new-parent –
你需要有全部7個進程在同一時間運行,或者連續地建造樹,當你走的時候,根/枝會死掉? p7應該是最後一個進程? –
而..爲什麼你不能只使用一些傳統的同步機制?像管子一樣。 –