My code is the following:

# include <stdio.h>
# include <sys/types.h>
# include <sys/ipc.h>
# include <sys/sem.h>
# include <unistd.h>
# include <stdlib.h>
# include <time.h>
# define NS 3


union semun {
   int	val; struct semid_ds *buf; ushort *array; 
};
int main(void)
{
   int sem_id, sem_value, i;  key_t ipc_key; struct semid_ds sem_buf;
   static ushort sem_array[NS] = {3, 1, 4}; union semun arg;
   ipc_key = ftok(".", 'S');

   /* Create semaphore */
   if ((sem_id = semget(ipc_key, NS, IPC_EXCL | IPC_CREAT | 0666)) == -1) {
      perror ("semget: IPC | 0666");
      exit(1);
   }
   printf ("Semaphore identifier %d\n", sem_id);
   /* Set arg (the union) to the address of the storage location for */
   /* returned semid_ds value */

   arg.buf = &sem_buf;
   if (semctl(sem_id, 0, IPC_STAT, arg) == -1) {
      perror ("semctl: IPC_STAT");
      exit(2);
   }
   printf ("Create %s", ctime(&sem_buf.sem_ctime));

   /* Set arg (the union) to the address of the initializing vector */
   arg.array = sem_array;

   if (semctl(sem_id, 0, SETALL, arg) == -1) {
      perror("semctl: SETALL");
      exit(3);
   }
   for (i=0; i<NS; ++i) {
      if ((sem_value = semctl(sem_id, i, GETVAL, 0)) == -1) {
         perror("semctl : GETVAL");
         exit(4);
      }
      printf ("Semaphore %d has value of %d\n",i, sem_value);
   }
}

It worked a few times, but now it just gives the following error from the CREAT | EXCL line:

semget: IPC | 0666: File exists

and when I run ipcs at the command line, I get:

------ Shared Memory Segments --------
key shmid owner perms bytes nattch status

------ Semaphore Arrays --------
key semid owner perms nsems

------ Message Queues --------
key msqid owner perms used-bytes messages

which indicates that there are no semaphores, right? So, I'm not sure how to get rid of something that "isn't there."

Any ideas?

nevermind... i logged out and back in and it seemed to have gotten rid of what was "stuck." thanks

This article has been dead for over six months. Start a new discussion instead.