#include #include #include #include #include int main() { int x = 100; pid_t pid; /* process id */ /* fork a child process */ pid = fork(); /*** fork() returns twice... ***/ if ( pid < 0 ) { fprintf( stderr, "ERROR: fork() failed.\n" ); exit( 1 ); } if ( pid == 0 ) /* child */ { printf( "CHILD: I'm new. Let me look around.\n" ); x++; printf( "CHILD: x is %d\n", x ); exit( 7 ); } else /* parent (pid > 0) */ { int status; /* return status from the child process */ pid_t child_pid; printf( "PARENT: created process id %d\n", pid ); /* wait until child terminates */ child_pid = wait( &status ); printf( "PARENT: child process id %d terminated", child_pid ); /* least-significant byte is non-zero if child terminated abnormally */ /* 00000000 00000000 00000111 00000000 */ if ( ( status & 0x000F ) != 0 ) { printf( " abnormally.\n" ); } else { int rc = status >> 8; /* shift right 8 bits */ rc = rc & 0x00FF; /* mask most-significant bytes */ printf( " with exit status %d.\n", rc ); } printf( "PARENT: x is %d\n", x ); } return 0; }