linux信号量,进程可以阻塞自己吗?

发布于 2024-10-08 13:05:18 字数 417 浏览 0 评论 0原文

我使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

赤濁 2024-10-15 13:05:18

据我目前所见,您应该:

  1. 将信号量初始化为1(su.val)

  2. 调用semop并将sb.sem_op设置为0(即等待计数器降至零)。

  3. 删除其他进程中的计数 (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:

  1. Initialize the semaphore to 1 (su.val)

  2. Call semop with sb.sem_op set to 0 (i. e. wait for counter to drop to zero).

  3. 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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文