make Runtime._syscall() protected so it can be overridden from outside the package
[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;
9     int status;
10     int i;
11     
12     pid = fork();
13     switch(pid) {
14         case -1: perror("fork"); break;
15         case 0: 
16             fprintf(stderr,"In the forked process (pid: %d), sleeping for 2 sec\n",getpid());
17             sleep(2);
18             fprintf(stderr,"Child done sleeping... exiting\n");
19             _exit(0);
20             break;
21         default:
22             fprintf(stderr,"In the main process (child is: %d) waiting for child\n",pid);
23             if(waitpid(pid,&status,0) < 0)
24                 perror("waitpid");
25             else
26                 fprintf(stderr,"Child process exited (status: %d)\n",status);
27     }
28  
29     pid = fork();
30     if(pid==0) {
31         fprintf(stderr,"1st fork (pid: %d)\n",getpid());
32         if(fork()==0) {
33             fprintf(stderr,"2nd fork (pid: %d).. sleeping\n",getpid());
34             sleep(5);
35             fprintf(stderr,"2nd fork exiting\n");
36             _exit(0);
37         }
38         fprintf(stderr,"1st fork (pid: %d) exiting\n",getpid());
39         _exit(0);
40     } else  {
41         waitpid(pid,NULL,0);
42         fprintf(stderr,"1st  fork terminated\n");
43     }
44     fprintf(stderr,"Sleeping for a bit\n");
45     sleep(10);
46     
47     fprintf(stderr,"Next few pids should be sequential\n");
48     for(i=0;i<10;i++) {
49         if(fork() == 0) {
50             fprintf(stderr,"I am a child %d\n",getpid());
51             sleep(i%4 + 5);
52             fprintf(stderr,"Child %d exiting\n",getpid());
53             _exit(0);
54         }
55     }
56     for(i=0;i<10;i++) fprintf(stderr,"Waited on %d\n",waitpid(-1,NULL,0));
57     
58     return 0;
59 }