如何使用fork()命令,以便产生10个进程并让它们同时执行一个小任务.
并发是一个有效的词,许多显示如何使用fork的地方只在他们的演示中使用一个fork()调用.我以为你会使用某种for循环,但我尝试过,在我的测试中,fork()似乎产生了一个新进程,正在做工作,然后产生一个新进程.所以它们似乎是按顺序运行但是如果有意义的话,我如何同时进行分叉并让10个进程同时进行工作?
谢谢.
更新:谢谢你的回答,我想我最初误解了fork()的一些方面,但我现在明白了.干杯.
解决方法
在循环中调用fork():
int numberOfChildren = 10; pid_t *childPids = NULL; pid_t p; /* Allocate array of child PIDs: error handling omitted for brevity */ childPids = malloc(numberOfChildren * sizeof(pid_t)); /* Start up children */ for (int ii = 0; ii < numberOfChildren; ++ii) { if ((p = fork()) == 0) { // Child process: do your work here exit(0); } else { childPids[ii] = p; } } /* Wait for children to exit */ int stillWaiting; do { stillWaiting = 0; for (int ii = 0; ii < numberOfChildren; ++ii) { if (childPids[ii] > 0) { if (waitpid(childPids[ii],NULL,WNOHANG) != 0) { /* Child is done */ childPids[ii] = 0; } else { /* Still waiting on this child */ stillWaiting = 1; } } /* Give up timeslice and prevent hard loop: this may not work on all flavors of Unix */ sleep(0); } } while (stillWaiting); /* Cleanup */ free(childPids);
原文地址:https://www.jb51.cc/c/117492.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。