Unix系统中system函数的返回值
2015-06-22 15:57
495 查看
网上关于system函数的返回值说明很多很详细但却不直观,这里搬出apue 3rd Editon中实现system函数的代码来说明其返回值。
其中
我们可以在
WIFEXITED(status)如果为真,那么表示子进程正常返回,我们通过执行
WIFSIGNALED(status)如果为真表面该子进程接收到某信号导致其abort,我们执行
WIFSTOPPED(status) 如果为真表面该子进程当前处于暂停状态,通过执行
#include <sys/wait.h> #include <errno.h> #include <unistd.h> int system(const char *cmdstring) { pid_t pid; int status; /* version without signal handling */ if (cmdstring == NULL) return(1); /* always a command processor with UNIX */ if ((pid = fork()) < 0) { status = -1; /* probably out of processes */ } else if (pid == 0) { /* child */ execl("/bin/sh", "sh", "-c", cmdstring, (char *)0); _exit(127); /* execl error */ } else { /* parent */ while (waitpid(pid, &status, 0) < 0) { if (errno != EINTR) { status = -1; /* error other than EINTR from waitpid() */ break; } } } return(status); }
其中
waitpid函数将子进程函数的返回值存储于
status变量中作为最后返回,该返回值又若干位组成不同位代表不同的退出状态,子进程返回可能是正常返回,可能是abort,可能是产生core文件....
我们可以在
<sys/wait.h>头文件中找到若干宏定义来定位子进程的退出状态。
#include "apue.h" #include <sys/wait.h> void pr_exit(int status) { if (WIFEXITED(status)) printf("normal termination, exit status = %d\n", WEXITSTATUS(status)); else if (WIFSIGNALED(status)) printf("abnormal termination, signal number = %d%s\n", WTERMSIG(status), #ifdef WCOREDUMP WCOREDUMP(status) ? " (core file generated)" : ""); #else ""); #endif else if (WIFSTOPPED(status)) printf("child stopped, signal number = %d\n", WSTOPSIG(status)); }
WIFEXITED(status)如果为真,那么表示子进程正常返回,我们通过执行
WEXITSTATUS(status)获取返回值。
WIFSIGNALED(status)如果为真表面该子进程接收到某信号导致其abort,我们执行
WTERMSIG(status)获取该导致该子进程退出的信号。
WIFSTOPPED(status) 如果为真表面该子进程当前处于暂停状态,通过执行
WSTOPSIG(status)获得导致该进程暂停的信号。
相关文章推荐
- /dev/kvm简单理解
- LexTreeLinguist API
- 新浪通行证在线申诉找回密码业务逻辑错误导致严重安全漏洞
- 01-复杂度1. 最大子列和问题(20)
- 由Android的fastboot no permissions而引出的Linux特殊权限管理之:SUID、SGID、SBIT
- 万物互联下的企业新生态
- session与cookie的区别和联系?
- 微信公共服务平台开发(.Net 的实现)1-------认证“成为开发者”
- Visual Studio 2012常用快捷键总结
- 冒泡排序
- UVa 658 It's not a Bug, it's a Feature!
- 判断输入的IP是否正确
- LexTreeHMMState API
- 组合数取模
- 02-线性结构2. 一元多项式求导 (25)
- 《你的灯还亮着吗》1
- LexTreeEndWordState API
- Oracle书籍推荐
- <transmission> element is used to link actuators to joints
- LexTreeEndUnitState API