Question

I'm trying to get this code working but I can't. I manage to create some code that doesn't show any compilation error or warning, but when I try to execute it fails with this error:

semget: No such file or directory

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <time.h>

int main(int argc, char *argv[]) {
   key_t llave1,llavesem;   
   int idmem,idsem; 
   struct sembuf op;    
   llavesem=ftok("/tmp",'b');

   idsem=semget(llavesem,1,0); /* This is the line giving the error*/
   if (idsem==-1) {
      perror ("semget");
      return 1;
   }

   semctl(idsem,1,SETVAL, &valini);
   op.sem_num=0;
   op.sem_flg=0;

   /*Some code here*/

   op.sem_op=-1;
   semop(idsem,&op,1);

   /*Some code here*/

   op.sem_op=1;
   semop(idsem,&op,1);
   semctl(idsem,1,IPC_RMID);
}

If I include the header file sys/sem.h ... why the executable file doesn't find it?

What I'm doing wrong?

Thanks in advance and best regards,

************** EDIT ****************

Following the answers given, I create the files, to do that I add this include:

   #include <fcntl.h>

And I add this two lines before the ftok sentence:

llave1=open("/tmp/a",O_RDWR|O_CREAT,0644);
llavesem=open("/tmp/b",O_RDWR|O_CREAT,0644);

The files are created but I still having the same error.

ubuntu@/: ls -l /tmp/a
 -rw-r--r-- 1 ubuntu ubuntu 0 Sep 11 00:11 /tmp/a 
ubuntu@/: ls -l /tmp/b
 -rw-r--r-- 1 ubuntu ubuntu 0 Sep 11 00:11 /tmp/b 

Any ideas?

Thanks!!

Was it helpful?

Solution

Have you created a semaphore in a separate process? If not then you should add the flag IPC_CREAT to have the system create a semaphore for you. If you don't specify this option and haven't created it in another process then there is no semaphore for you to get access to.

Be sure to also check http://linux.die.net/man/2/semget for further information.

OTHER TIPS

you should test if ftok call was a success or not before using it in semget (the first argument of ftok must refer to an existing, accessible file).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top