system函数

一、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;
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值