linux信号量,进程可以阻塞自己吗?
我使用semget()获取一个信号量,并将其VAL初始化为0,然后我想用semop()等待它,但它直接返回。 (另一个进程旨在获取SEM并在某些操作后释放它)
但是如果我获取SEM并在一个进程中将其VAL初始化为0,并在另一个进程中等待它,它就可以工作。
这是否意味着进程不能阻塞自身?
谢谢!!!
像这样:
int semid = semget(IPC_PRIVATE, 1, IPC_CREAT);
union semun su;
su.val = 0;
semctl(semid, 1, SETVAL, su);
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = -1;
sb.sem_flg = 0;
semop(semid, &sb, 1);
I use semget() to get a semaphore, and initialize its VAL to 0, then I want to wait it with semop(), but it directly return. (Another process is designed to get the SEM and release it after some operations)
But if I get a SEM and init its VAL to 0 in a process, and wait it in another process, it works.
Does it mean that a process cannot block itself?
thanks!!!
like this:
int semid = semget(IPC_PRIVATE, 1, IPC_CREAT);
union semun su;
su.val = 0;
semctl(semid, 1, SETVAL, su);
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = -1;
sb.sem_flg = 0;
semop(semid, &sb, 1);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
据我目前所见,您应该:
将信号量初始化为1(su.val)
调用semop并将sb.sem_op设置为0(即等待计数器降至零)。
删除其他进程中的计数 (sem_op = -1)。
因为您用 0 初始化了信号量,并调用将其减一(信号量永远不会低于零),所以您的等待调用将成功,并且您的进程不会阻塞。
这有帮助吗?
也许这可能会提供额外的见解:
http://linuxdevcenter.com/pub/a/linux/2007/05/24/semaphores-in-linux.html?page=2
As far as I can see at the moment you should:
Initialize the semaphore to 1 (su.val)
Call semop with sb.sem_op set to 0 (i. e. wait for counter to drop to zero).
Drop the count in the other process (sem_op = -1).
Because you initialized the semaphore with 0 and called to decrement it by one (semaphores never go below zero), your wait call will succeed and your process won't block.
Does that help?
Perhaps this may give additional insight:
http://linuxdevcenter.com/pub/a/linux/2007/05/24/semaphores-in-linux.html?page=2