我正在尝试学习使用信号量。我想做的是初始化一个信号量。然后将其值设置为 1,获取该值并打印它。但是每次我尝试这样做时,它都会显示-1。我的代码如下。提前致谢。
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <time.h>
#include <sys/ipc.h>
#include <sys/sem.h>
union semun {
int val;
struct semid_ds *buf;
ushort *array;
struct seminfo *__buf;
void *__pad;
};
int main(){
int pid, status, semid, value;
union semun semopts;
semid = semget(IPC_PRIVATE, 1, IPC_CREAT);
semopts.val = 1;
semctl(semid, 0, SETVAL, semopts);
value = semctl(semid, 0, GETVAL, 0);
printf("Value = %d\n", value);
return 0;
}