00001 /* 00002 Example using shared memory and semaphore (inefficient) 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 *sem; 00048 int *p, prev = 0, n; 00049 00050 ec_null( sem = SimpleSemOpen("shmexsem") ) 00051 ec_null( p = getaddr() ) 00052 while (true) { 00053 ec_false( SimpleSemWait(sem) ) 00054 n = *p; 00055 ec_false( SimpleSemPost(sem) ) 00056 if (n == 99) 00057 break; 00058 if (prev != n) { 00059 printf("child saw %d\n", n); 00060 prev = n; 00061 } 00062 } 00063 printf("child is done\n"); 00064 ec_false( SimpleSemClose(sem) ) 00065 } 00066 else { 00067 struct SimpleSem *sem; 00068 int *p, i; 00069 00070 ec_null( sem = SimpleSemOpen("shmexsem") ) 00071 ec_null( p = getaddr() ) 00072 *p = 0; 00073 ec_false( SimpleSemPost(sem) ) 00074 for (i = 1; i < 4; i++) { 00075 ec_false( SimpleSemWait(sem) ) 00076 *p = i; 00077 ec_false( SimpleSemPost(sem) ) 00078 sleep(1); 00079 } 00080 ec_false( SimpleSemWait(sem) ) 00081 *p = 99; 00082 ec_false( SimpleSemPost(sem) ) 00083 ec_false( SimpleSemClose(sem) ) 00084 } 00085 exit(EXIT_SUCCESS); 00086 00087 EC_CLEANUP_BGN 00088 exit(EXIT_FAILURE); 00089 EC_CLEANUP_END 00090 } 00091