/* shared.c - thanks to Ke Qui and Andy Barbacki for providing this program * Thanks to Nik Unger for removing errors/warnings. * for COSC 2P13, Spring 2011 * * Description: * The program prompts the user to enter a number, n. It then creates a child process with fork. * The child counts to n, incrementing a shared variable, p_shared (initially 0), with each iteration. * The parent counts to n and decrements the value of p_shared with each iteration. * Given that these processes run in parallel, the result should thus always be 0. * However, for sufficiently large n values, this is not the case . test this empirically by * compiling and running the code for various n values. */ #include #include #include #include #define CHILD 0 #define ERROR -1 int main () { int fork_value; /* the value returned by the fork() system call */ int status; /* used by the wait() system call */ int shmid; /* shared memory identifier returned by shmget() */ void *shmat_value; /* value returned by shmat() */ int *p_shared; /* a pointer to the shared int */ int i; /* a counter */ int n; /* the number times to loop */ struct shmid_ds buffer; /* buffer for result of shmctl */ printf ("How many times should the program run? "); scanf ("%d", &n); //set up interprocess communication via shared variable shmid = shmget(IPC_PRIVATE,4,444); /* 4 bytes, rw------- */ shmat_value = shmat(shmid, 0, 0); p_shared = shmat_value; *p_shared = 0; /* initialize shared variable */ fork_value = fork(); if (fork_value == ERROR) { printf ("fork() failed\n"); return 1; } if (fork_value == CHILD) /* child process */ { for (i=0; i < n; i++) { (*p_shared)++; /* add 1 */ } shmdt(shmat_value); /* cleanup */ } else /* parent process */ { for (i=0; i < n; i++) { (*p_shared)--; /* subtract 1 */ } wait(&status); /* wait for child to terminate */ printf ("%d\n", *p_shared); shmdt(shmat_value); /* cleanup */ shmctl(shmid, IPC_RMID, &buffer); } return 0; }