Linux C 獲取進程退出值的實現(xiàn)代碼
更新時間:2013年05月27日 15:18:39 作者:
本篇文章是對在Linux下使用c語言獲取進程退出值的方法進行了詳細的分析介紹,需要的朋友參考下
如以下代碼所示:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[])
{
pid_t pid;
int stat;
int exit_code;
pid = fork();
if(pid == 0)
{
sleep(3);
exit(5);
}
else if( pid < 0 )
{
fprintf(stderr, "fork failed: %s", strerror(errno));
return -1;
}
wait(&stat); // 等待一個子進程結束
if(WIFEXITED(stat)) // 如果子進程通過 return, exit, _exit 正常結束, WIFEXITED() 返回 true
{
exit_code = WEXITSTATUS(stat);
printf("child's exit_code: %d\n", exit_code);
}
return 0;
}
參考: "man 2 wait"
復制代碼 代碼如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, char *argv[])
{
pid_t pid;
int stat;
int exit_code;
pid = fork();
if(pid == 0)
{
sleep(3);
exit(5);
}
else if( pid < 0 )
{
fprintf(stderr, "fork failed: %s", strerror(errno));
return -1;
}
wait(&stat); // 等待一個子進程結束
if(WIFEXITED(stat)) // 如果子進程通過 return, exit, _exit 正常結束, WIFEXITED() 返回 true
{
exit_code = WEXITSTATUS(stat);
printf("child's exit_code: %d\n", exit_code);
}
return 0;
}
參考: "man 2 wait"
相關文章
C語言實現(xiàn)學生信息管理系統(tǒng)(文件版)
這篇文章主要為大家詳細介紹了C語言實現(xiàn)學生信息管理系統(tǒng),文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2020-07-07
C++實現(xiàn)LeetCode(30.串聯(lián)所有單詞的子串)
這篇文章主要介紹了C++實現(xiàn)LeetCode(30.串聯(lián)所有單詞的子串),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-07-07

