仔细阅读fork(2)手册页。多次阅读该页面,这很难理解。请阅读fork (system call)和processes (computing)上的Wikipage。
请理解 - 和这需要时间这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.
如果你希望能够到餐桌的多个进程,尝试:
增加RLIMIT_NPROC
资源限制setrlimit(2)(可能会调用系统设施,所以也看看/etc/pam.d/login
等
降低fork
-计划所需的资源。特别是降低堆内存要求
增加一些系统资源,如可能交换。你可以用一些临时文件swapon
进行测试。
由于Joachim Pileborg replied你应该避免分叉太多(分叉过程继续循环,从而也再次分叉)。
不要忘记stdio
例程被缓冲。适当地使用fflush(3)。
我建议你阅读Advanced Linux Programming这本书(可以在线获得),它有一个完整的章节解释Linux上的进程处理。
BTW,请与ps
或top
或pstree
你有多少(并与free
命令多少内存使用,但抱怨之前阅读http://linuxatemyram.com/)的过程。也可能发生这样的情况,即你的特定系统不能跨越你的特定程序超过24倍(因为缺乏资源)
也研究简单shell的源代码(如sash
)并使用strace -f
(例如在某些shell ,或者在你的程序中)来更多地了解系统调用的完成情况。还要学习如何使用gdb
调试器。
请在你的代码(名称,字符串,注释)用英语 –
请不要发布两次同样的问题... – Xymostech