一、写博原由
对system()函数的返回值仅判断 != 0 时为脚本执行失败,发现脚本有时没有执行,而程序却没报错,故出此博客。
仅有代码,详细可man system。
二、正确判断返回值代码示例
2.1 脚本示例
cdk.sh
#!/bin/sh
echo "hello world"
2.2 C语言执行脚本示例
写法1:对情况详细判断
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t status;
status = system("./cdk.sh");
if (-1 == status)
{
printf("system error\n");
return -1;
}
else
{
//正确退出
if (WIFEXITED(status))
{
if (0 == WEXITSTATUS(status))//操作成功
{
printf(“run successfully.\n");
}
else
{
printf("run fail, exit code: [%d]\n", WEXITSTATUS(status));
return -1;
}
}
else
{
printf("exit status = [%d]\n", WEXITSTATUS(status));
return -1;
}
}
return 0;
}
写法2:简易写法
#include <stdio.h>
#include <stdlib.h>
int main()
{
pid_t status;
status = system("./cdk.sh");
if (-1 == status)
{
printf("system error\n");
return -1;
}
//正确退出并操作成功
if (WIFEXITED(status)
&& 0 == WEXITSTATUS(status))
{
printf("run successfully.\n");
}
else
{
printf("fail, exit code: [%d]\n", WEXITSTATUS(status));
return -1;
}
return 0;
}