- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我想 fork 多个进程,然后对它们使用信号量。这是我尝试过的:
sem_init(&sem, 1, 1); /* semaphore*, pshared, value */
.
.
.
if(pid != 0){ /* parent process */
wait(NULL); /* wait all child processes */
printf("\nParent: All children have exited.\n");
.
.
/* cleanup semaphores */
sem_destroy(&sem);
exit(0);
}
else{ /* child process */
sem_wait(&sem); /* P operation */
printf(" Child(%d) is in critical section.\n",i);
sleep(1);
*p += i%3; /* increment *p by 0, 1 or 2 based on i */
printf(" Child(%d) new value of *p=%d.\n",i,*p);
sem_post(&sem); /* V operation */
exit(0);
}
输出是:
child(0) forkedchild(1) forked Child(0) is in critical section. Child(1) is in critical section.child(2) forked Child(2) is in critical section.child(3) forked Child(3) is in critical section.child(4) forked Child(4) is in critical section. Child(0) new value of *p=0. Child(1) new value of *p=1. Child(2) new value of *p=3. Child(3) new value of *p=3. Child(4) new value of *p=4.Parent: All children have exited.
这显然意味着信号量没有按预期工作。你能解释一下我应该如何在 fork 进程上使用信号量吗?
最佳答案
您遇到的问题是对sem_init()
函数的误解。当您阅读 manual page你会看到这个:
The pshared argument indicates whether this semaphore is to be shared between the threads of a process, or between processes.
如果你读到这里,你会认为 pshared 的非零值会使信号量成为进程间信号量。然而,这是错误的。您应该继续阅读,您将了解到必须在共享内存区域中定位信号量。为此,可以使用几个函数作为你可以在下面看到:
If pshared is nonzero, then the semaphore is shared between processes, and should be located in a region of shared memory (see shm_open(3), mmap(2), and shmget(2)). (Since a child created by fork(2) inherits its parent's memory mappings, it can also access the semaphore.) Any process that can access the shared memory region can operate on the semaphore using sem_post(3), sem_wait(3), etc.
我发现这种方法比其他方法更复杂,因此我想鼓励人们使用 sem_open()
而不是 sem_init()
。
下面你可以看到一个完整的程序说明如下:
#include <stdio.h> /* printf() */
#include <stdlib.h> /* exit(), malloc(), free() */
#include <sys/types.h> /* key_t, sem_t, pid_t */
#include <sys/shm.h> /* shmat(), IPC_RMID */
#include <errno.h> /* errno, ECHILD */
#include <semaphore.h> /* sem_open(), sem_destroy(), sem_wait().. */
#include <fcntl.h> /* O_CREAT, O_EXEC */
int main (int argc, char **argv){
int i; /* loop variables */
key_t shmkey; /* shared memory key */
int shmid; /* shared memory id */
sem_t *sem; /* synch semaphore *//*shared */
pid_t pid; /* fork pid */
int *p; /* shared variable *//*shared */
unsigned int n; /* fork count */
unsigned int value; /* semaphore value */
/* initialize a shared variable in shared memory */
shmkey = ftok ("/dev/null", 5); /* valid directory name and a number */
printf ("shmkey for p = %d\n", shmkey);
shmid = shmget (shmkey, sizeof (int), 0644 | IPC_CREAT);
if (shmid < 0){ /* shared memory error check */
perror ("shmget\n");
exit (1);
}
p = (int *) shmat (shmid, NULL, 0); /* attach p to shared memory */
*p = 0;
printf ("p=%d is allocated in shared memory.\n\n", *p);
/********************************************************/
printf ("How many children do you want to fork?\n");
printf ("Fork count: ");
scanf ("%u", &n);
printf ("What do you want the semaphore value to be?\n");
printf ("Semaphore value: ");
scanf ("%u", &value);
/* initialize semaphores for shared processes */
sem = sem_open ("pSem", O_CREAT | O_EXCL, 0644, value);
/* name of semaphore is "pSem", semaphore is reached using this name */
printf ("semaphores initialized.\n\n");
/* fork child processes */
for (i = 0; i < n; i++){
pid = fork ();
if (pid < 0) {
/* check for error */
sem_unlink ("pSem");
sem_close(sem);
/* unlink prevents the semaphore existing forever */
/* if a crash occurs during the execution */
printf ("Fork error.\n");
}
else if (pid == 0)
break; /* child processes */
}
/******************************************************/
/****************** PARENT PROCESS ****************/
/******************************************************/
if (pid != 0){
/* wait for all children to exit */
while (pid = waitpid (-1, NULL, 0)){
if (errno == ECHILD)
break;
}
printf ("\nParent: All children have exited.\n");
/* shared memory detach */
shmdt (p);
shmctl (shmid, IPC_RMID, 0);
/* cleanup semaphores */
sem_unlink ("pSem");
sem_close(sem);
/* unlink prevents the semaphore existing forever */
/* if a crash occurs during the execution */
exit (0);
}
/******************************************************/
/****************** CHILD PROCESS *****************/
/******************************************************/
else{
sem_wait (sem); /* P operation */
printf (" Child(%d) is in critical section.\n", i);
sleep (1);
*p += i % 3; /* increment *p by 0, 1 or 2 based on i */
printf (" Child(%d) new value of *p=%d.\n", i, *p);
sem_post (sem); /* V operation */
exit (0);
}
}
输出
./a.out
shmkey for p = 84214791
p=0 is allocated in shared memory.
How many children do you want to fork?
Fork count: 6
What do you want the semaphore value to be?
Semaphore value: 2
semaphores initialized.
Child(0) is in critical section.
Child(1) is in critical section.
Child(0) new value of *p=0.
Child(1) new value of *p=1.
Child(2) is in critical section.
Child(3) is in critical section.
Child(2) new value of *p=3.
Child(3) new value of *p=3.
Child(4) is in critical section.
Child(5) is in critical section.
Child(4) new value of *p=4.
Child(5) new value of *p=6.
Parent: All children have exited.
检查 shmkey
还不错,因为当 ftok()
失败时,它会返回 -1。但是,如果您有多个共享变量并且如果 ftok()
函数多次失败,具有值为 -1
的 shmkey
的共享变量将驻留在同一个共享内存的区域导致一个影响另一个的变化。因此程序执行会变得困惑。为避免这种情况,最好检查 ftok()
是否返回 -1(最好 checkin 源代码而不是像我那样打印到屏幕,尽管我想向您展示键值以防发生冲突)。
注意信号量是如何声明和初始化的。这与您在问题中所做的不同(sem_t sem
vs sem_t* sem
)。此外,您应该按照本例中出现的方式使用它们。您不能定义 sem_t*
并在 sem_init()
中使用它。
关于c - 如何在 C 中的 fork 进程上使用 POSIX 信号量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16400820/
有3个 repo : 有 OpenAI Baselines 存储库:https://github.com/openai/baselines . 我有它的 fork :https://github.co
我试图了解在调用 fork() 后复制文件描述符的含义及其对争用的可能影响。 在“Linux 编程接口(interface)”24.2.1 (p517) 中: When a fork() is per
我对 systemd 如何跟踪主进程存在后仍然存在的主进程的子进程感兴趣? 最佳答案 Systemd 为此使用了 cgroups。在启动任何使用服务文件定义的可执行文件之前,systemd 会创建一个
这是输出--- 家长:我的pid是4525 parent :我 parent 的 pid 是 3350 parent 开始- 4525 3350 fork 前 fork 前 child 4526 45
我之前 fork 了 jockm/vert.x 并向他发送了拉取请求。现在我想 fork vert-x/vert.x (jockm/vert.x 的上游)并向他们发送不同的拉取请求。但是,当我单击“F
我想控制从 Perl 脚本派生的进程的名称 a。理想情况下它会像这样: ./forker.pl | ... | | fork("forked.pl"); |\ | \ | `--------\ |
我知道 fork() 在更高级别上做什么。我想知道的是这个—— 一旦有 fork 调用,trap 指令就会跟随并且控制跳转以执行 fork “处理程序”。现在,这个创建子进程的处理程序如何通过创建另一
我正在研究操作系统测验,但我不知道输出什么 if(fork()) fork() 会产生。有人可以解释吗? 我不明白这一行: if(fork()) 编辑: 我所说的“输出”是指如果执行此代码,将
这个问题在这里已经有了答案: Why does this program print "forked!" 4 times? (6 个答案) 关闭 3 年前。 在 C 中,fork() 函数将为父进程
有什么方法可以区分程序中不同 fork() 函数创建的子进程。 global variable i; SIGCHLD handler function() { i--; } handle() {
我正在重新开发一个系统,该系统将通过 http 向多个供应商之一发送消息。原来是perl脚本,重新开发很可能也会用perl。 在旧系统中,同时运行多个 perl 脚本,每个供应商运行 5 个。当一条消
Git 的新手,仍然有点困惑。我在 github 上 fork 了一个项目,想将项目所有者最近对原始项目所做的一些更改引入/merge 到我的 fork 中。这可能吗?该项目是只读的,但基本上,我想让
根据维基百科(可能是错误的) When a fork() system call is issued, a copy of all the pages corresponding to the par
我需要帮助了解如何在 Go 中妖魔化进程。 package main import ( "fmt" "os" ) func start() { var procAttr os.Pro
我已经执行了这段代码。我知道消息的顺序是任意顺序的(因为我明确没有使用信号量)我的程序流程如何?为什么? 父级被执行,因此“baz”被打印一次。有人可以解释为什么不打印“bar”吗?为什么我得到“fo
这个问题已经有答案了: Why does this program print "forked!" 4 times? (6 个回答) 已关闭 5 年前。 我对 fork 进程有疑问。我有一个代码是 i
我在弄清楚如何使用在不同进程之间创建的列表时遇到了麻烦。我所拥有的是: FileList.h - 我创建的列表 #include "Node.h" typedef struct FileList {
好吧,所以我一直在 stackoverflow 上查找这个问题,并且肯定在谷歌上搜索了半个小时,但我得到的答案似乎与我真正想做的事情几乎没有任何关系,希望有人能提供帮助我在这方面,代码如下: int
我正在尝试了解 fork-join 的工作原理。 维基百科有以下合并排序示例,其中左半部分被 fork ,右半部分由当前线程处理。 mergesort(A, lo, hi): if lo t
下面的代码输出了一系列的过程,它到底做了什么: _PARENT_ / \ /
我是一名优秀的程序员,十分优秀!