//created by Dr. Ramsey on 10/25/13 //edits by Dr. Ramsey on 4/18/15 #include #include //needed for O_CREAT #include using namespace std; int main() { int current_value; char *name ="rams"; // this is the 'name' of my semaphore //open a named semaphore and create if it wasn't created //0644 describes the permissions //1 is the initial value of the semaphore sem_t *sem = sem_open(name, O_CREAT, 0644, 1); sem_getvalue(sem, ¤t_value); cout << "Before Entry: The current value of the semaphore is: " << current_value << endl; while(sem_wait(sem)); //the usual wait until we can subtract 1 - blocking system call sem_getvalue(sem, ¤t_value); cout << "Inside C.S: The current value of the semaphore is: " << current_value << endl; cout << "Inside the critical section doing things" << endl; //try wait will not block but report an error int getlock = sem_trywait(sem); if(getlock) { //then some error was reported cout << "Error reported from sem_trywait: " << getlock << endl; } sem_post(sem); //the usual add 1 sem_getvalue(sem, ¤t_value); cout << "After Exit: The current value of the semaphore is: " << current_value << endl; cout << "Input an integer to continue: "; cin >> current_value; //stop the program for demo purposes sem_close(sem); //disconnect this process from the semaphore //get rid of this semaphore sem_unlink(name); //will destroy if all are closed }