您的位置:首页 > 运维架构 > Linux

linux 操作系统 创建多个子进程

2017-04-17 22:47 351 查看
1、编写一段程序实现以下功能:

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)即可
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息