Reputation: 93
Here's a simple example:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/sem.h>
#include <signal.h>
#include <sys/shm.h>
#include <errno.h>
#include <time.h>
typedef union semun
{
int val;
struct semid_ds *buf;
ushort *array;
}semun;
int main(int argc, char *argv[]) {
int key = ftok("test.c", 1);
semun t;
int sem_id = semget(key, 1 , 0666 | IPC_CREAT | IPC_EXCL);
printf("%d", sem_id);
if(sem_id != -1){
printf("Creating a new semaphore...\n");
t.val = 1;
semctl(sem_id, 0, SETVAL, &t);
}
else if (errno == EEXIST) {
printf("Connecting...");
sem_id = semget(key, 1, 0);
}
else {
printf("LINUX Error");
exit(0);
}
struct sembuf P;
P.sem_num = 0;
P.sem_op = -1;
P.sem_flg = 0;
semop(sem_id, &P, 1);
printf("Hello\n");
semctl(sem_id, 0, IPC_RMID);
return 0;
}
The code bellow semop doesn't get printed out, yet I have an example of to me exactly the same code on the side which works. What could be wrong with this code? I've checked the semaphore array and emptied it before each run.
Upvotes: 1
Views: 41
Reputation: 93
The problem was with the & sign in this line.
semctl(sem_id, 0, SETVAL, &t);
Upvotes: 1