sync with my cvs
[nestedvm.git] / src / tests / Fork.c
1 #include <stdio.h>
2 #include <unistd.h>
3 #include <stdlib.h>
4 #include <sys/wait.h>
5
6 int main() {
7     fprintf(stderr,"In the main process (pid: %d), about to fork\n",getpid());
8     pid_t pid = fork();
9     int status;
10     int i;
11     
12     switch(pid) {
13         case -1: perror("fork"); break;
14         case 0: 
15             fprintf(stderr,"In the forked process (pid: %d), sleeping for 2 sec\n",getpid());
16             sleep(2);
17             fprintf(stderr,"Child done sleeping... exiting\n");
18             _exit(0);
19             break;
20         default:
21             fprintf(stderr,"In the main process (child is: %d) waiting for child\n",pid);
22             if(waitpid(pid,&status,0) < 0)
23                 perror("waitpid");
24             else
25                 fprintf(stderr,"Child process exited (status: %d)\n",status);
26     }
27  
28     pid = fork();
29     if(pid==0) {
30         fprintf(stderr,"1st fork (pid: %d)\n",getpid());
31         if(fork()==0) {
32             fprintf(stderr,"2nd fork (pid: %d).. sleeping\n",getpid());
33             sleep(5);
34             fprintf(stderr,"2nd fork exiting\n");
35             _exit(0);
36         }
37         _exit(0);
38     } else  {
39         waitpid(pid,NULL,0);
40         fprintf(stderr,"1st  fork terminated\n");
41     }
42     fprintf(stderr,"Sleeping for a bit\n");
43     sleep(10);
44     fprintf(stderr,"Next few pids should be sequential\n");
45     for(i=0;i<10;i++) {
46         if(fork() == 0) {
47             fprintf(stderr,"I am a child %d\n",getpid());
48             sleep(i%4);
49             _exit(0);
50         }
51     }
52     for(i=0;i<10;i++) fprintf(stderr,"Waited on %d\n",waitpid(-1,NULL,0));
53     
54     return 0;
55 }