一、system介绍
1、system简介
该函数用于执行一条 shell 命令。
二、system实现
1、函数原型
#include <stdlib.h>
int system(const char *command);
- 返回值:
status
:如果子进程创建失败,或者它的状态无法得到,则返回值为-1.WIFEXITED(status)
:如果子进程正常退出,则返回一个非零值。WEXITSTATUS(status)
:当 WIFEXITED 返回非零值时,可以使用这个宏来提取子进程的返回值。
三、system使用
1、system返回值判断
/* @return: 0 - ok, < 0 - err. */
int is_system_ok(int status)
{
if (-1 == status) {
printf("system error!");
return -1;
} else {
if (WIFEXITED(status)) {
if (0 == WEXITSTATUS(status)) {
return 0;
} else {
printf("run shell script fail, script exit code: %d\n", WEXITSTATUS(status));
return -1;
}
} else {
printf("exit status = [%d]\n", WEXITSTATUS(status));
return -1;
}
}
}
2、执行ls命令
#include <stdio.h>
#include <stdlib.h>
extern int is_system_ok(int status);
int main(int argc, char *argv[])
{
if (is_system_ok(system("ls")) {
printf("%s: system err!\n", __func__);
} else {
printf("%s: system ok!\n", __func__);
}
return 0;
}