Reputation: 387
so there's this assignment the teacher gave us, and she already gave us some a procedure to create semaphore along with some other procedures. I could create one a semaphore with that procedure but couldn't do more than one, the it shows an error when trying to create the second one. I really tried to look for a solution for this but I couldn't even find a code with a similar procedure. is there something I should change within the procedure "sem_create" ?
here's the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int sem_create(key_t CLEF,int initval) {
union semun {
int val;
struct semid_ds *buf;
ushort *array;
} arg_ctl;
int semid;
semid = semget(ftok("Disjktra.h<votre login>",CLEF),
1, IPC_CREAT|IPC_EXCL|0666);
if (semid == -1)
return -1;
arg_ctl.val = initval; // sth is missing here
if (semctl(semid, 0, SETVAL, arg_ctl) == -1)
return -1;
return semid;
}
/////////////////////////////////
/////////////////////////////////
void main() {
int i, CLE=33, S1=0, S2=0;
if ((S1 = sem_create(CLE,0)) == -1) {
perror("error in creating semaphore 1");
exit(-1);
}
if ((S2 = sem_create(CLE,0)) == -1) {
perror("error in creating semaphore 2");
exit(-1);
}
}
Output:
error in creating semaphore 2 :File exists
Upvotes: 0
Views: 3025
Reputation: 107
semaphore exclusivity
first time:
semget() returns the ID of the semaphore. and the check to see
if this value is greater than 0 results in a true thereby
execting the printf() that prints the ID
second time
the next time round howevever the value returned b semget() is
less than 0 signifying that the semaphore alread exists.
as a result the perror() function executed.
reason is :file exists
Upvotes: 0
Reputation: 5664
According to the Linux manual page for semget(2):
If semflg specifies both
IPC_CREAT
andIPC_EXCL
and a semaphore set already exists for key, thensemget()
fails with errno set toEEXIST
.
This seems pretty clear. Your sem_create
function calls semget
to create a "Disjktra.h" semaphore, but only if one does not already exist. You can't do that twice in the same program.
Edit: note also, from the ftok(3) man page:
The specified path must specify an existing file that is accessible to the calling process or the call will fail.
I believe that if you check the result of ftok
you will find that it is failing to generate a valid key for either semaphore:
key_t semkey = ftok("Disjktra.h<votre login>",CLEF);
if (semkey < 0) {
perror("error creating key");
return -1;
}
Based on this, I suggest using a real file for the pathname to ftok
, or abandoning ftok
entirely and creating a private semaphore each time with semget(IPC_PRIVATE, ...)
.
On another note, your code was very hard to understand the way it was formatted. Please consider cleaning up your code so it's easier to read when you post a question.
Upvotes: 1