/* Program to demonstrate shared memory IPC */ /* Written by Carey Williamson Jan 27, 2010 */ #include #include #include #define DEBUG 1 #define SLOW 1 int main() { pid_t pid; int i, num = 0; /* fork a child process */ pid = fork(); if( pid < 0 ) { /* error occurred */ fprintf(stderr, "Fork failed!\n"); return 1; } else if( pid == 0 ) { /* child process */ #ifdef DEBUG printf("\t\t\t\tI am the child! Here I go...\n"); #endif #ifdef SLOW sleep(1); #endif printf("\t\t\t\tChild process: num = %d\n", num); num = 1; printf("\t\t\t\tChild process sets num = %d\n", num); #ifdef SLOW sleep(3); #endif printf("\t\t\t\tChild process: num = %d\n", num); num = 3; printf("\t\t\t\tChild process sets num = %d\n", num); #ifdef SLOW sleep(5); #endif printf("\t\t\t\tChild process: num = %d\n", num); num = 5; printf("\t\t\t\tChild process sets num = %d\n", num); #ifdef SLOW sleep(7); #endif printf("\t\t\t\tThat was fun! All done now.\n"); } else { /* parent process */ #ifdef DEBUG printf("I am the parent!\n"); #endif #ifdef SLOW sleep(2); #endif printf("Parent process: num = %d\n", num); num = 2; printf("Parent process sets num = %d\n", num); #ifdef SLOW sleep(4); #endif printf("Parent process: num = %d\n", num); num = 4; printf("Parent process sets num = %d\n", num); #ifdef DEBUG printf("Waiting for child now...\n"); #endif wait(NULL); #ifdef DEBUG printf("All done, and my child too!\n"); #endif } }