进程控制开发之:实验内容
7.4实验内容
7.4.1编写多进程程序
1.实验目的
通过编写多进程程序,使读者熟练掌握fork()、exec()、wait()和waitpid()等函数的使用,进一步理解在Linux中多进程编程的步骤。
2.实验内容
该实验有3个进程,其中一个为父进程,其余两个是该父进程创建的子进程,其中一个子进程运行“ls-l”指令,另一个子进程在暂停5s之后异常退出,父进程先用阻塞方式等待第一个子进程的结束,然后用非阻塞方式等待另一个子进程的退出,待收集到第二个子进程结束的信息,父进程就返回。
3.实验步骤
(1)画出该实验流程图。
该实验流程图如图7.8所示。
图7.8实验7.4.1流程图
(2)实验源代码。
先看一下下面的代码,这个程序能得到我们所希望的结果吗,它的运行会产生几个进程?请读者回忆一下fork()调用的具体过程。
/*multi_proc_wrong.c*/
#includestdio.h>
#includestdlib.h>
#includesys/types.h>
#includeunistd.h>
#includesys/wait.h>
intmain(void)
{
pid_tchild1,child2,child;
/*创建两个子进程*/
child1=fork();
child2=fork();
/*子进程1的出错处理*/
if(child1==-1)
{
printf(Child1forkerrorn);
exit(1);
}
elseif(child1==0)/*在子进程1中调用execlp()函数*/
{
printf(Inchild1:execute'ls-l'n);
if(execlp(ls,ls,-l,NULL)0)
{
printf(Child1execlperrorn);
}
}
if(child2==-1)/*子进程2的出错处理*/
{
printf(Child2forkerrorn);
exit(1);
}
elseif(child2==0)/*在子进程2中使其暂停5s*/
{
printf(Inchild2:sleepfor5secondsandthenexitn);
sleep(5);
exit(0);
}
else/*在父进程中等待两个子进程的退出*/
{
printf(Infatherprocess:n);
child=waitpid(child1,NULL,0);/*阻塞式等待*/
if(child==child1)
{
printf(Getchild1exitcoden);
}
else
{
printf(Erroroccured!n);
}
do
{
child=waitpid(child2,NULL,WNOHANG);/*非阻塞式等待*/
if(child==0)
{
printf(Thechild2processhasnotexited!n);
sleep(1);
}
}while(child==0);
if(child==child2)
{
printf(Getchild2exitcoden);
}
else
{
printf(Erroroccured!n);
}
}
exit(0);
}
linux操作系统文章专题:linux操作系统详解(linux不再难懂)
评论