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

#include "myapue.h"
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>

void pr_exit(int status);
int system(const char *cmdstring);

int main(void)
{
	int status;

	if((status = system("date")) < 0)
		err_sys("system() error");	
	    
	pr_exit(status);//正常执行,正常退出

	if((status = system("nosuchcommand")) < 0)
		err_sys("system() error");	
	
	pr_exit(status);//exec失败(表示不能执行shell,其返回值如同shell执行了exit(127))

	if((status = system("who; exit 44")) < 0)
		err_sys("system() error");	
	
	pr_exit(status);//who正常执行,之后执行exit 44退出shell
}

<212>

int system(const char *cmdstring)
{
	pid_t pid;
	int status;

	if(cmdstring == NULL) 
		return(1);

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

(1)<212>

execl函数:取路径名作为参数,(l表示列表list:要求将新程序的每个命令行参数都说明为一个单独的参数,并以空指针结尾)

execlp函数:以文件名作为参数。

shell的-c选项告诉shell程序取下一个命令行参数作为命令输入。(cmdstring)

(2)

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

(3)

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


<191>

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));
}

(1)

wait和waitpid返回的终止状态,用定义在<sys/wait.h>中个各个宏来查看。有4个互斥的宏可用来取得进程终止的原因。

WIFEXITED(status):若为正常终止子进程返回的状态,则为真。

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

WIFSIGNALED(status):若为异常终止子进程返回的状态,则为真(接到一个不捕捉的信号)。

                         WTERMSIG(status):获取子进程终止的信号编号。

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

WIFSTOPPED(status):若为当前暂停子进程的返回状态,则为真。

                   WSTOPSIG(status):获取使子进程暂停的信号编号。

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值