我写了这段代码:http: //ideone.com/cNypUb
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void signchld (int signal){
fprintf (stderr, "[X] child exited\n");
}
int main(){
signal (SIGCHLD, signchld);
int i;
for(i=0;i<=300;i++){
pid_t f;
f=fork();
if(f==0){
//child
usleep(3*1000000);
fprintf (stderr, "[C1] %d\n",i);
exit(0);
fprintf (stderr, "[C2] %d\n",i);
}else if(f>0){
fprintf (stderr, "[P1] %d\n",i);
usleep(20000000);
fprintf (stderr, "[P2] %d\n",i);
}
}
return 0;
}
但[p2]
每 3 秒运行一次,然后运行下一个循环
我希望看到这个输出:
[P1] 0
[C1] 0
[X] child exited
20 秒后
[P2] 0
[P1] 1
[C1] 1
[X] child exited