user244050
user244050

Reputation: 5

Share array of Semaphores between two processes | linux C

Everyone, I'm here to ask you how can I share an array of semaphores between 2 process??Since I created an array with semget(..) but I can't use shmat(..) on it !

With shared memory segment I usually use shmget() first and then shmat(..) so the child process can access to it. But How it works with an array of semaphores?

I can't find any similar method able to attach() !!!

Here I Use the semget() to create an array of 5 semaphores:

/* allocate semaphores */
    if ((semid = semget(IPC_PRIVATE,5,IPC_CREAT|0666)) == -1) {
        printf("shmget() fallita sem id\n");
        perror("semget()");
        //releaseAll(bufferid,Tid,Did,semid);
        exit(-4);

Here in another process I try to attach this array before use it (but i'm using shmat and seems not working..)

sem_t* addr1;

    if((addr1=(sem_t*)shmat(semid,NULL,0))==-1){
        printf("shmat() fallita sem id\n");
        perror("shmat() for content");

        exit(-1);// +1 per \0 finale
    }

Upvotes: 0

Views: 2421

Answers (1)

Duck
Duck

Reputation: 27552

There are two kinds of semaphores available on linux: sysV and POSIX. You are using sysV semaphores.

sysV semaphores are maintained in the kernel so you don't need to allocate space for them or put them in shared memory to share them. But you do need a way for every process using them to find them. The mechanism to do that is key_t type.

The function ftok takes a pathname and an id and returns a key_t. This allows every process specifying the proper path and id to generate the same key_t.

semget takes the generated key_t, the number of requested semaphores, and some permissions flags and returns the semaphore identifier, that is the semid. The semid is used in all subsequent calls to semctl and semop.

An alternative, when you don't need to share the identity of the semaphore with other processes is to call semget with IPC_PRIVATE instead of a generated key_t. You are implicitly acknowledging by the use of IPC_PRIVATE that no unrelated processes need to know the returned semid and thus access the semaphore. This is useful for single processes with multiple threads that share memory and thus the semid; or for related processes that create the semaphores before forking but share a copy of the semid after the fork.

So your problem seems to be that you have two unrelated processes that need to share some semaphores. For that to work you need to use the ftok mechanism to generate the key so everyone involved can find them.

Upvotes: 4

Related Questions