c标准库函数——system()
声明:
int system(const char *command)
command为请求执行的shell命令构成的字符数组。
使用:
char command[50];
strcpy( command, "ls -l" ); //列出 unix 机上当前目录下所有的文件和目录
int status = system(command);
该函数执行的步骤是:
(1)在当前进程fork一个子进程;
(2)调用/bin/sh拉起shell脚本,在子进程中运行shell命令;
(3)返回子进程执行结果的状态值。
根据上面的步骤system()函数的返回值分为以下几种情况:
(1)如果子进程创建失败,则返回-1;
(2)当子进程成功创建后,我们需要判断shell脚本有没有正常执行结束(调用/bin/sh拉起shell脚本失败或者shell脚本执行过程中被强制kill掉都算异常),可以通过系统提供的宏WIFEXITED(status)来判断,如果WIFEXITED(status)为真,则说明正常结束。但是,注意!!! /bin/sh调用失败会返回127,没有执行权限返回126,此时WIFEXITED(status)也为真,注意与下一个步骤的返回值区分;
(3)当shell脚本正常执行结束后,shell的返回值被填到status的低8~15比特位中,我们同样可以通过系统提供的宏来获取状态值,此时使用WEXITSTATUS(status)。我们一般在shell脚本中会通过返回值判断本脚本是否正常执行,如果成功返回0,失败返回正数。
综上所述,判断一个system()调用shell脚本是否成功的准则是以下三个条件同时成立:
(1)-1 != status
(2)WIFEXITED(status)为真
(3)0 == WEXITSTATUS(status)
参考代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
int main()
{
pid_t status; // pid_t为一种typedef类型,其实就是int
status = system("./test.sh");
if (-1 == status)
{
printf("system error!");
}
else
{
printf("exit status value = [0x%x]\n", status);
if (WIFEXITED(status))
{
if (0 == WEXITSTATUS(status))
{
printf("run shell script successfully.\n");
}
else
{
printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status));
}
}
else
{
printf("exit status = [%d]\n", WEXITSTATUS(status));
}
}
return 0;
}