学习笔记——Linux下system()函数详解

system函数

system函数和exec函数一样,都是执行shell 命令,但是system比较顶,把execl函数封装起来,所以习惯上使用system函数

下面是手册的介绍

NAME
       system - execute a shell command//执行shell 命令

SYNOPSIS
       #include <stdlib.h>

       int system(const char *command);

DESCRIPTION
       system()  executes a command specified in command by calling /bin/sh -c
       command, and returns after the command has been completed.  During exe‐
       cution  of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT
       will be ignored.

接下来看看这个代码
参考:https://www.cnblogs.com/leijiangtao/p/4051387.html

先看linux版system函数的源码:
代码:

#include
#include
#include
#include

int system(const char * cmdstring)
{
  pid_t pid;
  int status;

  if(cmdstring == NULL){
      
      return (1);
  }


  if((pid = fork())<0){

        status = -1;
  }
  else if(pid == 0){
    execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
    -exit(127); //子进程正常执行则不会执行此语句
    }
  else{
        while(waitpid(pid, &status, 0) < 0){
          if(errno != EINTER){
            status = -1;
            break;
          }
        }
    }
    return status;
}

也就是我们传递参数system,system中的execl接收并完成执行指令。
execl(“/bin/sh”, “sh”, “-c”, cmdstring, (char *)0);
这句话中sh -c是执行命令的前缀,和“./”一样,比如我们运行执行文件,第一种是./demo 还有一种是sh -c demo

system()函数的返回值如下:
成功,则返回进程的状态值;
当sh不能执行时,返回127;
失败返回-1;

我们随便应用一下上一节的demo

#include <stdio.h>
#include <unistd.h>

int main(int argc ,char **argv){
	
	
	if(system("date") == -1){
		printf("execl filed!\n");
		
		perror("becasue");
	}
	printf("system successful\n");
	return 0;
}

system 只需要传递一个命令参数,调用execl,执行起来应该是sh -c date
看下结果:
在这里插入图片描述

注意

system函数在执行成功之后会回到原来的点继续向下执行,这也就是为啥结果中有打印system successful

而execl函数是执行失败后回到原来的点继续向下执行
注意区分

  • 9
    点赞
  • 46
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

石子君

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值