gpt4 book ai didi

c - fork 的子进程是否使用相同的信号量?

转载 作者:行者123 更新时间:2023-11-30 16:52:25 24 4
gpt4 key购买 nike

假设我创建了一个信号量。如果我 fork 了一堆子进程,它们仍然会使用相同的信号量吗?

另外,假设我创建一个内部有信号量并 fork 的结构。所有子进程是否仍然使用相同的信号量?如果不是,将结构+信号量存储在共享内存中是否允许子进程使用相同的信号量?

我真的很困惑我的 fork 子进程如何使用相同的信号量。

最佳答案

Let's say I create a semaphore. If I fork a bunch of child processes, will they all still use that same semaphore?

如果您使用 SysV IPC 信号量 (semctl),那么可以。如果您使用 POSIX 信号量 (sem_init),那么可以,但是 only if you pass a true value for the pshared argument创建并将其放置在共享内存中。

Also, suppose I create a struct with semaphores inside and forked. Do all the child processes still use that same semaphore? If not, would storing that struct+semaphores in shared memory allow the child processes to use the same semaphores?

“内部信号量”是什么意思?对 SysV IPC 信号量的引用将被共享,因为信号量不属于任何进程。如果您使用 POSIX 信号量,或者从 pthreads 互斥体和 condvars 构建某些内容,则需要使用共享内存和 pshared 属性(pthreads 也有 condvarsmutexes 的 pshared 属性)

请注意,出于这些目的,使用 MAP_SHARED 标志创建的匿名 mmap 算作(匿名)共享内存,因此无需实际创建命名共享内存段。 fork 后普通堆内存将不会被共享

关于c - fork 的子进程是否使用相同的信号量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41232540/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com