linux 操作系统 创建多个子进程
2017-04-17 22:47
351 查看
1、编写一段程序实现以下功能:
a) 使用系统调用fork()创建两个子进程
b) 各个子进程显示和输出一些提示信息和自己的进程标识符。
c) 父进程显示自己的进程ID和一些提示信息,然后调用waitpid()等待多个子进程结束,并在子进程结束后显示输出提示信息表示程序结束。
2、
创建两个子进程的代码如下:
程序使用fork()产生子进程,同时在子进程结束时return 0表示结束此子进程。这样就可以在父进程中继续创建子进程。
同理 多个子进程一样,多fork几次然后执行然后return0 出来。然后在父进程中waitpid(进程号,null,0)即可
a) 使用系统调用fork()创建两个子进程
b) 各个子进程显示和输出一些提示信息和自己的进程标识符。
c) 父进程显示自己的进程ID和一些提示信息,然后调用waitpid()等待多个子进程结束,并在子进程结束后显示输出提示信息表示程序结束。
2、
创建两个子进程的代码如下:
#include <unistd.h> #include <stdarg.h> #include <time.h> #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <stdlib.h> int tprintf (const char *fnt,...); int main(void) { pid_tpid1,pid2; inti; printf("Hellofrom parent process,pid is %d.\n",getpid()); pid1=fork(); if(pid1==0) { sleep(1); for(i=0;i<3;i++) { tprintf("Hellofrom child NO.1 process %d. %d times\n",getpid(),i+1); sleep(1); } return0; } pid2=fork(); if(pid2==0) { sleep(1); for(i=0;i<3;i++) { tprintf("Hellofrom child NO.2 process %d. %dtimes\n",getpid(),i+1); sleep(1); } return0; } elseif(pid1!=-1) { tprintf("parentforked one child pross--%d.\n",pid1); tprintf("parentforked one child pross--%d.\n",pid2); tprintf("parentis waiting for child exit .\n"); waitpid(pid1,NULL,0); tprintf("childNO.1 process had exited .\n"); waitpid(pid2,NULL,0); tprintf("childNO.2 process had exited .\n"); tprintf("parentprocess had exited .\n"); } else { tprintf("every thing was done withouterror.\n");} return0; } int tprintf (const char *fnt,...) { va_listargs; structtm *tstruct; time_ttsec; tsec=time(NULL); tstruct=localtime(&tsec); printf("%02d:%02d:%02d:%5d|",tstruct->tm_hour,tstruct->tm_min,tstruct->tm_sec,getpid()); va_start(args,fnt); returnvprintf(fnt,args); }
程序使用fork()产生子进程,同时在子进程结束时return 0表示结束此子进程。这样就可以在父进程中继续创建子进程。
同理 多个子进程一样,多fork几次然后执行然后return0 出来。然后在父进程中waitpid(进程号,null,0)即可
相关文章推荐
- linux中创建多个子进程的方法
- 【Linux操作系统分析】进程——进程切换,进程的创建和撤销
- Linuxc:创建与监控多个子进程
- Linux下创建两个子进程,并在子进程异常退出时重新创建
- 【操作系统】linux创建子进程--fork()方法
- Linux中fork同时创建多个子进程的方法(二)
- Linux操作系统分析之进程的创建与可执行程序的加载
- Linux操作系统学习_用户进程之由新进程创建到可执行程序的加载
- Linux操作系统分析-lab2-进程的创建与可执行程序的加载
- [Linux进程]使用fork函数创建多个子进程
- 进程控制:linux中fork同时创建多个子进程注意事项
- 进程信号Linux操作系统分析(2)- 进程的创建与可执行程序的加载
- 【Linux操作系统分析】进程的创建与可执行程序的加载
- 【操作系统】linux创建子进程--fork()方法
- linux中fork同时创建多个子进程的方法(二)
- 【Linux操作系统分析】进程——进程切换,进程的创建和撤销
- Linux操作系统分析(2)- 进程的创建与可执行程序的加载
- Linux操作系统分析-(2)进程的创建与可执行程序的加载
- 【操作系统】linux创建子进程--fork()方法
- Linux 创建多个子进程