// demo shared variables and interference #include #include #include #include int *x; // int MAX = 10; int MAX = 100000000; C0() { int i; int tmp; for (i=1; i<=MAX; i++) { *x = *x + 1; // printf("x = %d\n", *x); } exit(1); } C1() { int i; int tmp; for (i=1; i<=MAX; i++) { *x = *x+1; // printf(" x = %d\n", *x); } // exit(1); } main() { int pid; int shmid, shm_address; int NUM_SHARED_VARS = 1; if ((shmid = shmget(IPC_PRIVATE, sizeof(int), 0600)) == -1) { printf("Error in shmget"); exit(0); } if ((int) (shm_address = shmat(shmid, 0, 0)) == -1) { printf("Error in shmat"); exit(0); } x = (int *) shm_address; *x = 0; pid = fork(); if (pid == 0) { C0(); } else { C1(); while (wait(NULL) >= 0 || errno != ECHILD) continue; printf("\nThe final value of x is: %d\n\n", *x); if (shmdt(shm_address) == -1) { printf("Error in shmdt"); exit(0); } if (shmctl(shmid, IPC_RMID, (struct shmid_ds *)0) == -1) { printf("Error in shmctl"); exit(0); } return 0; } }