00001 /* 00002 Example using shared memory and two semaphores 00003 AUP2, Sec. 7.13.2 00004 00005 Copyright 2003 by Marc J. Rochkind. All rights reserved. 00006 May be copied only for purposes and under conditions described 00007 on the Web page www.basepath.com/aup/copyright.htm. 00008 00009 The Example Files are provided "as is," without any warranty; 00010 without even the implied warranty of merchantability or fitness 00011 for a particular purpose. The author and his publisher are not 00012 responsible for any damages, direct or incidental, resulting 00013 from the use or non-use of these Example Files. 00014 00015 The Example Files may contain defects, and some contain deliberate 00016 coding mistakes that were included for educational reasons. 00017 You are responsible for determining if and how the Example Files 00018 are to be used. 00019 00020 */ 00021 #include "defs.h" 00022 #include <sys/shm.h> 00023 #include "SimpleSem.h" 00024 00025 static int *getaddr(void) 00026 { 00027 key_t key; 00028 int shmid, *p; 00029 00030 (void)close(open("shmseg", O_WRONLY | O_CREAT, 0)); 00031 ec_neg1( key = ftok("shmseg", 1) ) 00032 ec_neg1( shmid = shmget(key, sizeof(int), IPC_CREAT | PERM_FILE) ) 00033 ec_neg1( p = shmat(shmid, NULL, 0) ) 00034 return p; 00035 00036 EC_CLEANUP_BGN 00037 return NULL; 00038 EC_CLEANUP_END 00039 } 00040 /*[pgm]*/ 00041 int main(void) 00042 { 00043 pid_t pid; 00044 00045 ec_false( SimpleSemRemove("shmexsem") ) 00046 if ((pid = fork()) == 0) { 00047 struct SimpleSem *semR, *semW; 00048 int *p, n; 00049 00050 ec_null( semR = SimpleSemOpen("shmexsemR") ) 00051 ec_null( semW = SimpleSemOpen("shmexsemW") ) 00052 ec_null( p = getaddr() ) 00053 while (true) { 00054 ec_false( SimpleSemWait(semR) ) 00055 n = *p; 00056 ec_false( SimpleSemPost(semW) ) 00057 if (n == 99) 00058 break; 00059 printf("child saw %d\n", n); 00060 } 00061 printf("child is done\n"); 00062 ec_false( SimpleSemClose(semR) ) 00063 ec_false( SimpleSemClose(semW) ) 00064 } 00065 else { 00066 struct SimpleSem *semR, *semW; 00067 int *p, i; 00068 00069 ec_null( semR = SimpleSemOpen("shmexsemR") ) 00070 ec_null( semW = SimpleSemOpen("shmexsemW") ) 00071 ec_null( p = getaddr() ) 00072 *p = 0; 00073 ec_false( SimpleSemPost(semW) ) 00074 for (i = 1; i < 4; i++) { 00075 ec_false( SimpleSemWait(semW) ) 00076 *p = i; 00077 ec_false( SimpleSemPost(semR) ) 00078 sleep(1); 00079 } 00080 ec_false( SimpleSemWait(semW) ) 00081 *p = 99; 00082 ec_false( SimpleSemPost(semR) ) 00083 ec_false( SimpleSemClose(semR) ) 00084 ec_false( SimpleSemClose(semW) ) 00085 } 00086 exit(EXIT_SUCCESS); 00087 00088 EC_CLEANUP_BGN 00089 exit(EXIT_FAILURE); 00090 EC_CLEANUP_END 00091 } 00092