/******************************************************************************* * semaphore.c * This file is part of "Lab 4: sum of prime numbers of integer numbers" * Copyright (C) 2009 - c506001 (email: c506001@cse.hcmut.edu.vn ) * * Content: * -------- * Implementation of semaphore * * System and Networking Department * Faculty of Computer Science and Engineering * Ho Chi Minh City University of Technology ******************************************************************************/ #include #include #include #include #include #include #include /** * Function name: seminit * Description: * Create new semaphore * Then initialize its value is 1 * Return value: * semid: If successful * exit: Otherwise **/ int seminit() { int semid; // create new semaphore if ((semid=semget(IPC_PRIVATE,1,0666|IPC_EXCL))==-1){ perror("Error in creating a new semaphore"); exit(1); } // initialize semaphore's value is 1 union { int val; struct semid_ds *buf; ushort *array; } carg; //TODO: initialize carg if (semctl(semid,0,SETVAL,carg)==-1){ perror("Error in initializing semaphore"); exit(1); } return semid; } /** * Function name: P * Description: * Wait for semaphore's value greater than 0 * Decrease semaphore's value by 1 * Return value: * exit if error in decreasing semaphore's value **/ void P(int semid){ struct sembuf pbuf; //TODO: initialize pbuf // decrease semaphore's value by 1 if (semop(semid,&pbuf,1)==-1) { perror("Error in decreasing semaphore's value"); exit(1); } } /** * Function name: V * Description: * Signal processes waiting for semaphore * Increase semaphore's value by 1 * Return value: * exit if error in increasing semaphore's value **/ void V(int semid){ struct sembuf vbuf; //TODO: initialize vbuf // increase semaphore's value by 1 if (semop(semid,&vbuf,1)==-1) { perror("Error in increasing semaphore's value"); exit(1); } } /** * Function name: semrem * Description: * Remove an existing semaphore * Return value: * 0: If successful * -1: Otherwise **/ int semrem(int semid){ return semctl(semid,0,IPC_RMID,0); }