热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

APUE学习笔记system、prexit(打印wait函数返回的终止状态)

2019独角兽企业重金招聘Python工程师标准#includemyapue.h#include#include#inclu

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

#include "myapue.h"
#include 
#include 
#include void pr_exit(int status);
int system(const char *cmdstring);int main(void)
{int status;if((status &#61; system("date")) < 0)err_sys("system() error"); pr_exit(status);//正常执行&#xff0c;正常退出if((status &#61; system("nosuchcommand")) < 0)err_sys("system() error"); pr_exit(status);//exec失败&#xff08;表示不能执行shell&#xff0c;其返回值如同shell执行了exit(127)&#xff09;if((status &#61; system("who; exit 44")) < 0)err_sys("system() error"); pr_exit(status);//who正常执行&#xff0c;之后执行exit 44退出shell
}

<212>

int system(const char *cmdstring)
{pid_t pid;int status;if(cmdstring &#61;&#61; NULL) return(1);if((pid &#61; fork()) < 0)status &#61; -1;else if(pid &#61;&#61; 0){execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);_exit(127);}else{while(waitpid(pid, &status, 0) < 0){if(errno !&#61; EINTR){status &#61; -1;break;}}}return(status);
}

&#xff08;1&#xff09;<212>

execl函数&#xff1a;取路径名作为参数&#xff0c;&#xff08;l表示列表list&#xff1a;要求将新程序的每个命令行参数都说明为一个单独的参数&#xff0c;并以空指针结尾&#xff09;

execlp函数&#xff1a;以文件名作为参数。

shell的-c选项告诉shell程序取下一个命令行参数作为命令输入。&#xff08;cmdstring&#xff09;

&#xff08;2&#xff09;

调用_exit函数&#xff0c;而不是exit函数&#xff0c;防止任一标准I/O缓冲在子进程中被冲洗。

&#xff08;3&#xff09;

使用system而不是直接使用fork和exec的优点是&#xff0c;system进行了所需的各种出错处理&#xff0c;以及各种信号处理。


<191>

void pr_exit(int status)
{if(WIFEXITED(status))printf("normal termination, exit status &#61; %d\n", WEXITSTATUS(status));else if(WIFSIGNALED(status))printf("abnormal termination, signal number &#61; %d%s\n", WTERMSIG(status),
#ifdef WCOREDUMPWCOREDUMP(status) ? " (core file generated)" : "");
#else"");
#endif else if(WIFSTOPPED(status))printf("child stopped, signal number &#61; %d\n", WSTOPSIG(status));
}

&#xff08;1&#xff09;

wait和waitpid返回的终止状态&#xff0c;用定义在中个各个宏来查看。有4个互斥的宏可用来取得进程终止的原因。

WIFEXITED(status)&#xff1a;若为正常终止子进程返回的状态&#xff0c;则为真。

                   WEXITSTATUS(status)&#xff1a;获取子进程传送给exit或_exit参数的低8位。

WIFSIGNALED(status)&#xff1a;若为异常终止子进程返回的状态&#xff0c;则为真&#xff08;接到一个不捕捉的信号&#xff09;。

                         WTERMSIG(status)&#xff1a;获取子进程终止的信号编号。

                         WCOREDUMP(status)&#xff1a;若已产生终止进程的core文件&#xff0c;则返回真。&#xff08;使用前检查是否定义宏#ifdef WCOREDUMP&#xff09;

WIFSTOPPED(status)&#xff1a;若为当前暂停子进程的返回状态&#xff0c;则为真。

                   WSTOPSIG(status)&#xff1a;获取使子进程暂停的信号编号。


转:https://my.oschina.net/u/2463708/blog/509705



推荐阅读
author-avatar
手机用户2502863087
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有