/* * semSysV1.c++ shows the use of System V * semaphore as mutex lock * $ g++ -Wall semSysV1.c++ */ #include using namespace std; #include #include #include #include #include #include #include #define FLAGS (0644) static int P(int semID) { struct sembuf buff ; buff.sem_num = 0 ; // On the 0th element buff.sem_op = -1 ; buff.sem_flg = 0 ; if(semop(semID, &buff, 1) == -1) { cerr << "semop P operation error\n" ; return -1; } return 0 ; } static int V(int semID) { struct sembuf buff ; buff.sem_num = 0 ; // On the 0th element buff.sem_op = 1 ; buff.sem_flg = 0 ; if(semop(semID, &buff, 1) == -1) { cerr << "semop V operation error\n" ; return -1 ; } return 0 ; } int main() { int semID, chID ; if((semID = semget(IPC_PRIVATE, 1, IPC_CREAT | FLAGS)) == -1) { cerr << "semget() fails\n" ; exit(1) ; } semctl(semID, 0, SETVAL, 1); chID = fork(); if(chID == -1){ cerr << "fork() fails\n"; exit(1); } if(chID > 0) { // Parent int status ; for(int i=0; i<=5; ++i) { P(semID) ; cout << "Indian Institute of"; fflush(stdout); sleep(2); cout << " Information Technology\n"; V(semID) ; sleep(1) ; } waitpid(chID, &status, 0) ; semctl(semID, 0, IPC_RMID) ; } else { // Child for(int i=0; i<=5; ++i) { P(semID) ; cout << "Allahabad "; fflush(stdout); sleep(1); cout << "Bhubaneswar "; fflush(stdout); sleep(1); cout << "Kalyani\n"; V(semID) ; sleep(2) ; } } return 0 ; }