/* Shaun Cooper January 23, 2005 simple demonstration of shared memory segments and forked processes. Output: the output of the shared array updated by processes 1 and 2 */ #include #include #include #include #include /* value to size the array */ #define MAXNUM 10000 /* define the arrays */ /* a pointer to the shared memory segment */ int *in; /* simple routine to start up to child processes and place values into a shared memory segment */ main() { int status1, status2; int i,j; int done; int beg,mid,end; int level; int share_key_in; int share_key_out; pid_t child1, child2; struct shmid_ds item; /* define shared memory */ if ( (share_key_in=shmget(IPC_PRIVATE,MAXNUM * 4 , IPC_CREAT|0666)) < 0) perror("Cannot get shared memory\n"); /* attach shared memory segment */ if ( (in=shmat(share_key_in,(void *) 0, 0)) == (void *) -1) perror("cannot attach to shared memory\n"); /* simple array initialization of the shared memory segment */ for (j=0; j< MAXNUM; j++) { in[j]=0; } /* start up child 1 */ child1=fork(); if ( child1==0) { /* shared memory is already attached due to the rules of fork() */ in[1]=1; exit(0); /* child 1 is now out */ } else { /* start up child 2 */ child2=fork(); if (child2==0) { /* sahred memory for second child already attached by rule*/ in[2]=2; } else { /* parent process */ /* waitpid(child1,&status1, 0); waitpid(child2, &status2, 0); */ /* ONLY the parent process should destroy the shared memory segment*/ printf("%d %d %d \n", in[0],in[1],in[2]); /* should get 0, 1, 2 */ shmctl(share_key_in,IPC_RMID,&item); } } }