国产成人精品三级麻豆,色综合天天综合高清网,亚洲精品夜夜夜,国产成人综合在线女婷五月99播放,色婷婷色综合激情国产日韩

當(dāng)前位置:首頁(yè) > 嵌入式培訓(xùn) > 嵌入式學(xué)習(xí) > 講師博文 > 多進(jìn)程編程中父進(jìn)程如何回收僵尸進(jìn)程,經(jīng)典中的經(jīng)典

多進(jìn)程編程中父進(jìn)程如何回收僵尸進(jìn)程,經(jīng)典中的經(jīng)典 時(shí)間:2018-06-27      來(lái)源:未知

多進(jìn)程編程中會(huì)可能會(huì)產(chǎn)生僵尸進(jìn)程,這些僵尸進(jìn)程不斷蠶食系統(tǒng)資源,是系統(tǒng)變得越來(lái)越慢直至死亡,這種情況在并發(fā)模型中體現(xiàn)的尤為突出。這里分析下我們?cè)诙噙M(jìn)程編程中如何解決這樣的問(wèn)題。

首先我們寫(xiě)一個(gè)例子:

#include

#include

#include

int main(int argc, char **argv)

{

int pid;

pid = fork();

if (pid > 0) {

printf("this is parent process, pid = %d\n", getpid());

while(1);

} else if (pid == 0) {

printf("this is child process, pid = %d\n", getpid());

printf("child process exit\n");

} else {

printf("create child process failed\n");

}

return 0;

}

本例中: 父進(jìn)程創(chuàng)建子進(jìn)程,進(jìn)程完成移動(dòng)工作后退出。運(yùn)行效果如下:

this is parent process, pid = 3538

this is child process, pid = 3539

child process exit

使用ps -aux查看進(jìn)程狀態(tài)

此時(shí)父進(jìn)程3538狀態(tài)為R+而子進(jìn)程狀態(tài)為Z+,通過(guò)查看ps命令文檔可的如下說(shuō)明:

按照幫助文檔中說(shuō)明:R為運(yùn)行態(tài),Z為僵尸(zombie)態(tài)。

回收僵尸進(jìn)程我們可以用如下方法:

使用wait()或waitpid()函數(shù)。

#include

#include

pid_t wait(int *status);

pid_t waitpid(pid_t pid, int *status, int options);

wait: 父進(jìn)程調(diào)用等待任一子進(jìn)程退出。等同于waitpid(-1, &status, 0);

waitpid:

  

使用waitpid回收僵尸進(jìn)程,如下:

C++ Code

#include

#include

#include

#include

#include

int main(int argc, char **argv)

{

int pid, cpid;

pid = fork();

if (pid > 0) {

printf("this is parent process, pid = %d\n", getpid());

while(1) {

cpid = waitpid(-1, NULL, 0);

fprintf(stdout, "waitpid pid = %d: %s\n", cpid, strerror(errno));

sleep(1);

}

} else if (pid == 0) {

printf("this is child process, pid = %d\n", getpid());

printf("child process exit\n");

} else {

printf("create child process failed\n");

}

return 0;

}

運(yùn)行結(jié)果:

this is parent process, pid = 4085

this is child process, pid = 4086

child process exit

waitpid pid = 4086: Success

waitpid pid = -1: No child processes

waitpid pid = -1: No child processes
  ps -aux查看發(fā)現(xiàn)原來(lái)程序運(yùn)行過(guò)程僵尸態(tài)的子進(jìn)程已經(jīng)不在了。已經(jīng)不在了。

上一篇:進(jìn)程標(biāo)識(shí)符詳解,讓你對(duì)進(jìn)程標(biāo)識(shí)符有深入理解

下一篇:busybox文件系統(tǒng)制作步驟,帶你快速學(xué)習(xí)

熱點(diǎn)文章推薦
華清學(xué)員就業(yè)榜單
高薪學(xué)員經(jīng)驗(yàn)分享
熱點(diǎn)新聞推薦
前臺(tái)專線:010-82525158 企業(yè)培訓(xùn)洽談專線:010-82525379 院校合作洽談專線:010-82525379 Copyright © 2004-2022 北京華清遠(yuǎn)見(jiàn)科技集團(tuán)有限公司 版權(quán)所有 ,京ICP備16055225號(hào)-5京公海網(wǎng)安備11010802025203號(hào)

回到頂部