[英]Semaphore in C for shared memory can't initialize
The command semctl always returns -1 (returns "Fail2" in console). 命令semctl始终返回-1(在控制台中返回“ Fail2”)。 What am I doing wrong?
我究竟做错了什么?
union semun{
int val;
struct semid_ds *buf;
unsigned short int *array;
struct seminfo *__buf;
} forsem;
forsem.val = 0;
int sem;
if((sem= semget(key, 1, 0666 | IPC_CREAT) == -1)) {
fprintf(stderr, "Fail1");
}
if (semctl(sem, 0, SETVAL, forsem) == -1) {
fprintf(stderr, "Fail2");
}
Errno writes Invalid argument
Errno写入
Invalid argument
You make a simple mistake: in 您犯了一个简单的错误:
if((sem= semget(key, 1, 0666 | IPC_CREAT) == -1)) { fprintf(stderr, "Fail1"); }
You should write 你应该写
if((sem= semget(key, 1, 0666 | IPC_CREAT)) == -1) { fprintf(stderr, "Fail1"); }
Notice the brackets? 注意括号吗?
By the way, the error is EIDRM
because sem
is 0 in your code, not Invalid Argument
. 顺便说一句,错误是
EIDRM
因为在您的代码中sem
为0,而不是Invalid Argument
。
Thanks for your answer! 感谢您的回答! It does not matter.
不要紧。 The only thing it's not giving error is for
semctl
with the second argument 0 (number of the semaphore in the semaphore set), if I put 1 or 30 there, it returns -1. 唯一不会出错的地方是带有第二个参数0(信号量集中信号量的编号)的
semctl
,如果我在其中输入1或30,它将返回-1。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.