gpt4 book ai didi

c - fork() 的子进程过多

转载 作者:行者123 更新时间:2023-11-30 18:42:03 25 4
gpt4 key购买 nike

代码:

for ( ii = 0; ii < 24; ++ii) {

switch (fork()) {

case -1 : {
printf("\n\nproblem with fork() !!! \n\n");
exit(0);
};

case 0 : {
WriteOnShared_Mem(ii);
}break;
default : {
ChildPidTab[ii] = p;
usleep(50000);
ReadShared_MemMp(nbSect, 24,ChildPidTab);
};
}
}

我的问题是我有太多 child (nbenfant = 24),我有超过 24 个:/

这是我今天在这里发表的第 3 篇文章,但仍未解决:(

谢谢

最佳答案

仔细阅读fork(2)手册页。那一页读了好几遍,很难理解。另请阅读维基页面 fork (system call)以及 processes (computing) .

请理解 - 这需要时间 - fork 在成功时同时返回两次:一次在父级中,一次在子级中

由于多种原因,fork 系统调用可能会失败(然后返回 -1)。如果fork失败,请使用perror或其他方式显示errno。并且您应该始终保留fork的结果。所以代码

for (ii = 0; ii < 24; ++ii) {
fflush(NULL);
pid_t p = fork();
switch (p) {
case -1 : // fork failed
printf("\n\nproblem with fork() in pid %d error %s!!! \n\n",
(int) getpid(), strerror(errno));
exit(EXIT_FAILURE);
break;
case 0: // child process
WriteOnShared_Mem(ii);
ii = MAX_INT; // to stop the for loop
break;
default: // parent process
ChildPidTab[ii] = p;
/// etc.... some synchronization is needed
break;
}

特别是,fork 可能会失败,因为

   EAGAIN fork() cannot allocate sufficient memory to copy the
parent's page tables and allocate a task structure for
the child.
EAGAIN It was not possible to create a new process because the
caller's RLIMIT_NPROC resource limit was encountered. To
exceed this limit, the process must have either the
CAP_SYS_ADMIN or the CAP_SYS_RESOURCE capability.
ENOMEM fork() failed to allocate the necessary kernel structures
because memory is tight.

如果您希望能够派生更多进程,请尝试:

  • 使用 setrlimit(2) 增加 RLIMIT_NPROC 资源限制(这可能由系统设施调用,因此还要查看 /etc/pam.d/login

  • 减少fork-ing程序所需的资源。特别是,降低堆内存要求

  • 增加一些系统资源,例如交换。您可以交换一些临时文件进行测试。

Joachim Pileborg replied您应该避免 fork 太多( fork 的进程继续循环,因此也会再次 fork )。

不要忘记 stdio 例程是有缓冲的。使用fflush(3)适本地。

我建议阅读Advanced Linux Programming本书(可在线获取),其中有一整章解释了 Linux 上的进程处理。

顺便说一句,请使用 pstoppstree 检查您有多少个进程(以及使用 free命令使用了多少内存,但在提示之前请先阅读http://linuxatemyram.com/)。您的特定系统可能无法 fork 特定程序超过 24 次(因为缺乏资源)

还可以研究简单 shell 的源代码(例如 sash)并使用 strace -f(例如在某些 shell 或您的程序上)来了解更多系统调用完成。另请了解如何使用 gdb 调试器。

关于c - fork() 的子进程过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18549411/

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