進(jìn)程控制開(kāi)發(fā)之:實(shí)驗內容
編譯和運行以上代碼,并觀(guān)察其運行結果。它的結果是我們所希望的嗎?
看完前面的代碼之后,再觀(guān)察下面的代碼,它們之間有什么區別,會(huì )解決哪些問(wèn)題。
/*multi_proc.c*/
#includestdio.h>
#includestdlib.h>
#includesys/types.h>
#includeunistd.h>
#includesys/wait.h>
intmain(void)
{
pid_tchild1,child2,child;
/*創(chuàng )建兩個(gè)子進(jìn)程*/
child1=fork();
/*子進(jìn)程1的出錯處理*/
if(child1==-1)
{
printf(Child1forkerrorn);
exit(1);
}
elseif(child1==0)/*在子進(jìn)程1中調用execlp()函數*/
{
printf(Inchild1:execute'ls-l'n);
if(execlp(ls,ls,-l,NULL)0)
{
printf(Child1execlperrorn);
}
}
else/*在父進(jìn)程中再創(chuàng )建進(jìn)程2,然后等待兩個(gè)子進(jìn)程的退出*/
{
child2=fork();
if(child2==-1)/*子進(jìn)程2的出錯處理*/
{
printf(Child2forkerrorn);
exit(1);
}
elseif(child2==0)/*在子進(jìn)程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)在確保沒(méi)有編譯錯誤后,使用交叉編譯該程序:
$arm-linux-gccmulti_proc.c–omulti_proc(或者使用Makefile)
(5)將生成的可執行程序下載到目標板上運行。
4.實(shí)驗結果
在目標板上運行的結果如下所示(具體內容與各自的系統有關(guān)):
$./multi_proc
Inchild1:execute'ls-l'/*子進(jìn)程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/*子進(jìn)程2的顯示*/
Infatherprocess:/*以下是父進(jìn)程顯示*/
Getchild1exitcode/*表示子進(jìn)程1結束(阻塞等待)*/
Thechild2processhasnotexited!/*等待子進(jìn)程2結束(非阻塞等待)*/
Thechild2processhasnotexited!
Thechild2processhasnotexited!
Thechild2processhasnotexited!
Thechild2processhasnotexited!
Getchild2exitcode/*表示子進(jìn)程2終于結束了*/
因為幾個(gè)子進(jìn)程的執行有競爭關(guān)系,因此,結果中的順序是隨機的。讀者可以思考,怎樣才可以保證子進(jìn)程的執行順序呢?
linux操作系統文章專(zhuān)題:linux操作系統詳解(linux不再難懂)
評論