Linux Kernel Architecture

(Jacob Rumans) #1

Chapter 5: Locking and Interprocess Communication


void init_sem() {
/* Test whether semaphore already exists */
semid = semget(SEMKEY, 0, IPC_CREAT | PERMS);
if (semid < 0) {
printf("Create the semaphore\n");

semid = semget(SEMKEY, 1, IPC_CREAT | PERMS);
if (semid < 0) {
printf("Couldn’t create semaphore!\n");
exit(-1);
}

/* Initialize with 1 */
res = semctl(semid, 0, SETVAL, 1);
}
}

void down() {
/* Perform down operation */
res = semop(semid, &op_down[0], 1);
}

void up() {
/* Perform up operation */
res = semop(semid, &op_up[0], 1);
}

int main(){
init_sem();
/* Normal program code. */

printf("Before critical code\n");
down();
/* Critical code */
printf("In critical code\n");
sleep(10);
up();

/* Remaing program code */
return 0;
}

A new semaphore with a permanently defined magic number ( 1234 ) is first created inmainfor purposes
of identification within the system. Because several copies of the program are to run in parallel, it is
necessary to test whether a corresponding semaphore already exists. If not, one is created. This is done
using thesemgetsystem call to reserve a semaphore set. It requires the following parameters: the magic
number (SEMKEY), the number of semaphores in the set ( 1 ), and the desired access permissions. The above
sample program creates a semaphore set with just a single semaphore. The access permissions indicate
that all users have both read and write access to the semaphore.^8 Then the value of the single semaphore
in the semaphore set is initialized to 1 using thesemctlsystem call. Thesemidvariable identifies the
semaphore in the kernel (it can be obtained with the help of the magic number of any other program).

(^8) IPC_CREATis a system constant that must be ‘‘ORed‘‘with the access number to specify that a new semaphore is to be created.

Free download pdf