00001
00002 #ifndef IPC_SIMPLE_SEMAPHORE_H
00003 #define IPC_SIMPLE_SEMAPHORE_H
00004
00005
00006
00007
00008
00009 #include "simple.sem.H"
00010
00011 #ifdef linux
00012
00013 #include <sys/types.h>
00014 #include <sys/ipc.h>
00015 #include <sys/sem.h>
00016
00017 #include <iostream.h>
00018 #include <stdio.h>
00019 #include <stdlib.h>
00020
00021
00022 union semun {
00023 int val;
00024 struct semid_ds *buf;
00025 unsigned short *array;
00026 struct seminfo *__buf;
00027 };
00028
00029 class IPC_SimpleSemaphore : public SimpleSemaphore
00030 {
00031 protected:
00032 int _id;
00033
00034 int v_op()
00035 {
00036 struct sembuf sops[1];
00037 sops[0].sem_num = 0;
00038 sops[0].sem_op = 1;
00039 sops[0].sem_flg = 0;
00040 if (semop(_id, sops, 1) == -1)
00041 return 0;
00042 else
00043 return 1;
00044 }
00045
00046 int p_op()
00047 {
00048 struct sembuf sops[1];
00049 sops[0].sem_num = 0;
00050 sops[0].sem_op = -1;
00051 sops[0].sem_flg = 0;
00052
00053 if (semop(_id, sops, 1) == -1)
00054 return 0;
00055 else
00056 return 1;
00057 }
00058
00059 public:
00060 IPC_SimpleSemaphore(int key) : SimpleSemaphore(key), _id(0) {}
00061
00062 virtual int create() {
00063 int nsems = 1;
00064 _id = semget((key_t)_key, nsems, IPC_CREAT | IPC_EXCL | 0666);
00065 if (_id == -1) {
00066 return 0;
00067 } else {
00068
00069 union semun argument;
00070 argument.val = 0;
00071 if (semctl(_id, 0, SETVAL, argument) < 0) {
00072 cerr << "IPC_SimpleSemaphore: constructor cannot set semaphore value." << endl;
00073 return 0;
00074 }
00075
00076
00077 if (!v_op()) {
00078 cerr << "IPC_SimpleSemaphore: constructor couldn't do initial v-operation" << endl;
00079 return 0;
00080 }
00081
00082 _valid = 1;
00083 return 1;
00084 }
00085 }
00086
00087 virtual int attach() {
00088 _id = semget((key_t)_key, 0, 0);
00089
00090 if (_id == -1)
00091 return 0;
00092
00093 _valid = 1;
00094 return 1;
00095 }
00096
00097 virtual int remove() {
00098 if (semctl(_id, 0, IPC_RMID) == -1)
00099 return 0;
00100 else
00101 return 1;
00102 }
00103
00104
00105 virtual int lock() {
00106 return p_op();
00107 }
00108
00109 virtual int unlock() {
00110 return v_op();
00111 }
00112
00113 virtual void print( int do_wait=1 )
00114 {
00115
00116 struct semid_ds buf;
00117 union semun arg;
00118 arg.buf = &buf;
00119
00120 int s = semctl(_id, 0, IPC_STAT, &arg);
00121 if (s==0) {
00122 cerr << " value: " << semctl(_id, 0, GETVAL) << endl;
00123 cerr << " permissions:" << endl;
00124 cerr << " uid: " << int(buf.sem_perm.uid) << endl;
00125 cerr << " mode: " << int(buf.sem_perm.mode) << endl;
00126 cerr << " nsems: " << int(buf.sem_nsems) << endl;
00127 } else {
00128 cerr << "unable to get IPC_STAT info..." << endl;
00129 }
00130
00131 system ("ipcs -s");
00132
00133 if (do_wait) {
00134 cerr << "Type a number and <return> to continue..." << endl;
00135 int tmp;
00136 cin >> tmp;
00137 }
00138 }
00139 };
00140
00141 #endif
00142
00143 #endif
00144