File: wait_test.cpp

package info (click to toggle)
fakeroot-ng 0.16-1
  • links: PTS
  • area: main
  • in suites: squeeze
  • size: 940 kB
  • ctags: 580
  • sloc: sh: 3,746; cpp: 3,527; ansic: 1,408; makefile: 66
file content (53 lines) | stat: -rw-r--r-- 1,087 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main( int argc, char *argv[] )
{
    int numchildren=1;

    if( argc==2 ) {
        numchildren=strtoul( argv[1], 0, NULL );
    }

    for( int i=0; i<numchildren; ++i ) {
        pid_t child=fork();

        if( child==0 ) {
            // We are the child
            int exitcode=getpid()%253;
            printf("Child %d(%d) exit with code 0x%x\n", i+1, getpid(), exitcode );

            exit(exitcode);
        } else if( child==-1 ) {
            perror("Failed to fork");
        }
    }

    sleep(1);

    for( int i=0; i<numchildren; ++i ) {
        int status;

        pid_t process=wait(&status);

        if( process<0 ) {
            perror("wait failed");
        } else {
            printf("PID %d returned 0x%x\n", process, status);
        }
    }

    int status;
    pid_t process=wait(&status);

    if( process<0 ) {
        perror("Second wait failed");
    } else {
        printf("PID %d returned 0x%x\n", process, status);
    }

    return 0;
}