C++ 下system()函数的一些记录

system()函数在<cstdlib>头文件里
函数格式为
int system( const char* command );
当调用此函数时,需要输入我们平时常用的linux命令,例如system("ls"),它就会列出文件夹下的所有文件。

而他的返回值则大有学问:
system函数对返回值的处理,涉及3个阶段:
阶段1:创建子进程等准备工作。如果失败,返回-1。
阶段2:调用/bin/sh拉起shell脚本,如果拉起失败或者shell未正常执行结束(见下面的引用),其返回值如同shell执行了exit(127)一样,也可能会返回126。
阶段3:如果shell脚本正常执行结束,那system返回的是shell的return状态或者正常的终止状态。

  1. 只要能够调用到/bin/sh,并且执行shell过程中没有被其他信号异常中断,都算正常结束。

比如:不管shell脚本中返回什么原因值,是0还是非0,都算正常执行结束。即使shell脚本不存在或没有执行权限,也都算正常执行结束。

  1. 如果shell脚本执行过程中被强制kill掉等情况则算未正常执行结束。

如何确定shell正常运行结束了呢?
系统提供了宏:WIFEXITED(status)。如果WIFEXITED(status)为真,则说明正常结束。
如何获取shell返回值?
可以通过使用系统提供的宏WEXITSTATUS(status)
返回值 = status>>8

宗上所述,我们要判断shell脚本是否正常执行,应该满足下面3个条件。

-1!=status # 阶段1
WIFEXITED(status)==true # 阶段2
0 == WEXITSTATUS(status) # 阶段3,当shell脚本不存在、没有执行权限等场景下时,以上前2个条件仍会成立,此时WEXITSTATUS(status)为127,126等数值。

示例程序,system传入乱字符。

#include <stdio.h>
#include <stdlib.h>

int main(void){
    
    
	pid_t status = system("wrqwqwd");

	if (-1 == status){
    
    
		printf("返回-1,fork失败了,或者waitpid返回除了EINTR之外的错误\n");
		
		return 0;
	}
	else{
    
    
		printf("exit status value = [0x%x]\n", status);

		if (WIFEXITED(status)){
    
    
			if (0 == WEXITSTATUS(status)){
    
    
				printf("0 == WEXITSTATUS(status),运行完毕\n");
			}
			else{
    
    
				printf("0 != WEXITSTATUS(status),script exit code: %d\n", WEXITSTATUS(status));
				return 0;
			}
		}
		else{
    
    
			printf("WIFEXITED(status)为假,exit status = [%d]\n", WEXITSTATUS(status));
			return 0;
		}
	}
	return 0;
} 
-----------------------------
程序返回:
sh: 1: wrqwqwd: not found
exit status value = [0x7f00]           # 0x7f00 10进制为32512 右移8= 127
0 != WEXITSTATUS(status),script exit code: 127

如果shell没有正常运行结束,比如信号中断,或者command命令不存在,system()函数返回127。
传入常用的命令ls

pid_t status = system("ls");
-----------------------------
程序返回:
sh: 1: wrqwqwd: not found
exit status value = [0x00]           
0 != WEXITSTATUS(status),script exit code: 0

成功执行,返回0
传入没有权限的文件

pid_t status = system("./a.sh");
-----------------------------
程序返回:
sh: 1: wrqwqwd: not found
exit status value = [0x7e00]           
0 != WEXITSTATUS(status),script exit code: 126

shell脚本没有权限返回126。

Reference
https://ikaros.blog.csdn.net/article/details/103934689?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-3.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-3.no_search_link
https://blog.csdn.net/sabrina0115/article/details/8789555

猜你喜欢

转载自blog.csdn.net/xiaokai1999/article/details/120385021