进程控制开发之:实验内容
编译和运行以上代码,并观察其运行结果。它的结果是我们所希望的吗?
看完前面的代码之后,再观察下面的代码,它们之间有什么区别,会解决哪些问题。
/*multi_proc.c*/
#includestdio.h>
#includestdlib.h>
#includesys/types.h>
#includeunistd.h>
#includesys/wait.h>
intmain(void)
{
pid_tchild1,child2,child;
/*创建两个子进程*/
child1=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);
}
}
else/*在父进程中再创建进程2,然后等待两个子进程的退出*/
{
child2=fork();
if(child2==-1)/*子进程2的出错处理*/
{
printf(Child2forkerrorn);
exit(1);
}
elseif(child2==0)/*在子进程2中使其暂停5s*/
{
printf(Inchild2:sleepfor5secondsandthenexitn);
sleep(5);
exit(0);
}
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);
}
(3)首先在宿主机上编译调试该程序:
$gccmulti_proc.c–omulti_proc(或者使用Makefile)
(4)在确保没有编译错误后,使用交叉编译该程序:
$arm-linux-gccmulti_proc.c–omulti_proc(或者使用Makefile)
(5)将生成的可执行程序下载到目标板上运行。
4.实验结果
在目标板上运行的结果如下所示(具体内容与各自的系统有关):
$./multi_proc
Inchild1:execute'ls-l'/*子进程1的显示,以下是“ls–l”的运行结果*/
total28
-rwxr-xr-x1davidroot2322008-07-1804:18Makefile
-rwxr-xr-x1davidroot87682008-07-2019:51multi_proc
-rw-r--r--1davidroot14792008-07-2019:51multi_proc.c
-rw-r--r--1davidroot34282008-07-2019:51multi_proc.o
-rw-r--r--1davidroot14632008-07-2018:55multi_proc_wrong.c
Inchild2:sleepfor5secondsandthenexit/*子进程2的显示*/
Infatherprocess:/*以下是父进程显示*/
Getchild1exitcode/*表示子进程1结束(阻塞等待)*/
Thechild2processhasnotexited!/*等待子进程2结束(非阻塞等待)*/
Thechild2processhasnotexited!
Thechild2processhasnotexited!
Thechild2processhasnotexited!
Thechild2processhasnotexited!
Getchild2exitcode/*表示子进程2终于结束了*/
因为几个子进程的执行有竞争关系,因此,结果中的顺序是随机的。读者可以思考,怎样才可以保证子进程的执行顺序呢?
加入微信
获取电子行业最新资讯
搜索微信公众号:EEPW
或用微信扫描左侧二维码