Unexpected semaphore identifier

I tried following code:


#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/types.h>

#define SEM_KEY 1000
#define SEM_PERM 0600

int main(void)
{
	int sem_id;

	// create one semaphore
	if(sem_id = semget(SEM_KEY, 1, SEM_PERM | IPC_CREAT) == -1)
	{
		printf(" ERROR: Create semaphore: %s !
", strerror(errno));
		exit(1);
	}
	else
		printf(" SUCCESS: Semaphore id: %d.
", sem_id);

	// set semaphore initial value to 1
	if(semctl(sem_id, 0, SETVAL, 1) == -1)
	{
		printf(" ERROR: Set semaphore %d: %s !
", sem_id, strerror(errno));
		exit(1);
	}
	else
		printf(" SUCCESS: Semaphore %d set to value 1.
", sem_id);
	
	system("ipcs -s");

	exit(0);
}

This is the program output:

dan@linux-z9my:/mnt/hgfs/Labs/lab7> ./semaphore
SUCCESS: Semaphore id: 0.
ERROR: Set semaphore 0: Identifier removed !

Running system command “ipcs -s” give:

dan@linux-z9my:/mnt/hgfs/Labs/lab7> ipcs -s

------ Semaphore Arrays --------
key semid owner perms nsems
0x000003e8 655360 dan 600 1
0x4d03c9b8 425985 dan 600 8

As you see the semaphore was created, but its semid is not 0, like I expected.
Instead its semid is 655360, which is not an integer at all.

Is it a bug in the semaphore implementation ?

My FAULT !

The code should be:


// create one semaphore
	if( (sem_id = semget(SEM_KEY, 1, SEM_PERM | IPC_CREAT)) == -1)


I omitted 2 parenthesis !

Sorry !

Yes, good old C pitfall.

A friend of mine encountered a related pitfall, using shmem: The address returned by reading the shmem pseudofile in /proc is in decimal, but he printed the id in his debug printf in hex. They were the same value but it wasn’t immediately apparent to him.