/* * semaphorePOS1.c++ shows the use of POSIX * named semaphore as mutex lock * $ g++ -Wall semaphorePOS1.c++ -lpthread */ #include using namespace std; #include #include #include #include #include #include #include #include int main() { int i, cPID, status; sem_t *sP; sP = sem_open("/abcd", O_CREAT, 0777, 1); if(sP == SEM_FAILED && errno != EEXIST){ cerr << errno << " Semaphore error\n"; exit(1); } cPID = fork(); if(cPID == -1){ cerr << "fork() fails\n"; exit(1); } if(cPID != 0) { // Parent for(i=1; i<=5; ++i) { sem_wait(sP); // get lock cout << "Indian Institute of"; fflush(stdout); sleep(2); cout << " Information Technology\n"; sem_post(sP); // relese lock sleep(1); } waitpid(cPID, &status, 0); sem_close(sP); } else { // Child for(i=1; i<=5; ++i) { sem_wait(sP); // get lock cout << "Allahabad "; fflush(stdout); sleep(1); cout << "Bhubaneswar "; fflush(stdout); sleep(1); cout << "Kalyani\n"; sem_post(sP); // relese lock sleep(2); } } return 0 ; }