linux同时创建多进程的方法
来源:互联网 发布:怎么看淘宝的注册时间 编辑:程序博客网 时间:2024/06/06 11:45
自己第一次写创建多个进程的程序时不加思索地用循环,类似如下,
for(i=0; i<3; i++)
{
pid =fork();
if(pid==0)
{
child_process();
}
}
结果运行之后的结果很奇怪,因为父进程创建出来的子进程又会创建子进程,所以像一棵树一样创建下去,而不是所有子进程皆以主进程为父亲!
正确的方法应该是像引文中一样,如下;
法一
1.#include<stdio.h>
2.#include<stdlib.h>
3.#include<unistd.h>
4.pid_t pid;
5./*
6. * num:当前已经创建的子进程数
7. * max:需要创建的子进程数
8. */
9.void createsubprocess(int num,int max)
10.{
11. if(num>=max)return;
12. pid=fork();
13. if(pid<0)
14. {
15. perror("fork error!\n");
16. exit(1);
17. }
18. //子进程
19. else if(pid==0)
20. {
21. sleep(3);
22. printf("子进程id=%d,父进程id=%d\n",getpid(),getppid());
23. }
24. //父进程
25. else
26. {
27. num++;
28. if(num==1)printf("父进程id=%d\n",getpid());
29. if(num<max)createsubprocess(num,max);
30. //此处加sleep是为了防止父进程先退出,从而产生异常
31. sleep(5);
32. }
33.}
34.int main()
35.{
36. int num=0;
37. int max=3;
38. createsubprocess(num,max);
39. return 0;
40.}
法二
1.#include<stdio.h>
2.#include<stdlib.h>
3.#include<unistd.h>
4./*
5. * 创建指定数目的子进程
6. */
7.void createsubprocess(int num)
8.{
9. pid_t pid;
10. int i;
11. for(i=0;i<num;i++)
12. {
13. pid=fork();
14. //子进程或创建进程失败均退出
15. if(pid==0||pid==-1)
16. {
17. break;
18. }
19. }
20. if(pid==-1)
21. {
22. perror("fail to fork!\n");
23. exit(1);
24. }
25. else if(pid==0)
26. {
27. printf("子进程id=%d,其对应的父进程id=%d\n",getpid(),getppid());
28. exit(0);
29. }
30. else
31. {
32. printf("父进程id=%d\n",getpid());
33. exit(0);
34. }
35.}
36.int main()
37.{
38. int num=3;
39. createsubprocess(num);
40. return 0;
41.}
唉,竟然能用递归实现,小小崇拜一下^^ 不知道第一个写上面这样代码人是如何想到的! 也许大多数人都会想到用“无耻的”循环吧!
- linux同时创建多进程的方法
- linux中fork同时创建多个子进程的方法
- linux中fork同时创建多个子进程的方法(一)
- linux中fork同时创建多个子进程的方法(二)
- Linux中fork同时创建多个子进程的方法(二)
- linux中fork同时创建多个子进程的方法(一)
- fork同时创建多个子进程的方法
- Fork同时创建多个子进程方法
- linux创建进程方法
- linux中创建多个子进程的方法
- linux几种创建进程的方法
- linux几种创建进程的方法
- linux创建进程fork的方法步骤
- linux几种创建进程的方法
- 进程控制:linux中fork同时创建多个子进程注意事项
- Linux进程的创建
- Linux进程的创建
- Linux进程的创建
- Python字符串
- 解决Android:Installation error: INSTALL_FAILED_MEDIA_UNAVAILABLE问题
- jenkins maven配置
- Android对象序列化(二)-----Intent传递对象的两种方法(Serializable,Parcelable)
- Expressions are not allowed at the top level
- linux同时创建多进程的方法
- 软件测试流程
- Reverse Integer C++
- 欢迎使用CSDN-markdown编辑器
- postgresql 判断参数是否为空,拼接字符串的条件查询
- C++ 多线程
- webapp地址
- 生动详细解释javascript的冒泡和捕获
- 删除Chrome地址栏自动补齐的某个URL