Linux 笔记--system 函数执行shell指令

一、system函数介绍

system 函数执行shell指令。

功能:

①执行指定的shell指令

②执行文件(文件具有执行权限)中的指令

头文件:

#include <stdlib.h>

函数原型:

int system(const char *command);

官方介绍:

DESCRIPTION
       The  system()  library  function uses fork(2) to create a child process
       that executes the shell command specified in command using execl(3)  as
       follows:


           execl("/bin/sh", "sh", "-c", command, (char *) 0);


       system() returns after the command has been completed.


       During  execution  of  the command, SIGCHLD will be blocked, and SIGINT
       and SIGQUIT will be ignored, in the process that calls system()  (these
       signals  will  be  handled according to their defaults inside the child
       process that executes command).


       If command is NULL, then system() returns a status indicating whether a
       shell is available on the system.

返回值介绍:

RETURN VALUE
       The return value of system() is one of the following:


       *  If command is NULL, then a nonzero value if a shell is available, or
          0 if no shell is available.


       *  If a child process could not be created, or its status could not  be
          retrieved, the return value is -1.


       *  If  a  shell  could  not  be executed in the child process, then the
          return value is as though the  child  shell  terminated  by  calling
          _exit(2) with the status 127.


       *  If  all  system calls succeed, then the return value is the termina‐
          tion status of the child shell used to execute command.  (The termi‐
          nation  status of a shell is the termination status of the last com‐
          mand it executes.)


       In the last two cases, the return value is a "wait status" that can  be
       examined using the macros described in waitpid(2).  (i.e., WIFEXITED(),
       WEXITSTATUS(), and so on).


       system() does not affect the wait status of any other children.

二、测试例程

测试代码:

#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>


#define FILE_PATH "./config"//存在,且具有执行权限
#define FILE_PATH2 "./config2"//不存在


int main(int argc,char*argv[])
{
  int ret;
  //可执行
  printf("1\n");
  ret=system("ls");
  printf("ret=%d\n",ret);
  printf("%d:%s\n",errno,strerror(errno));
  //不可执行
  printf("2\n");
  ret=system("lt");
  printf("ret=%d\n",ret);
  printf("%d:%s\n",errno,strerror(errno));
  //可执行
  printf("3\n");
  ret=system(FILE_PATH);
  printf("ret=%d\n",ret);
  printf("%d:%s\n",errno,strerror(errno));
  //不可执行
  printf("4\n");
  ret=system(FILE_PATH2);
  printf("ret=%d\n",ret);
  printf("%d:%s\n",errno,strerror(errno));
  
  return 0;
}

测试结果:

df283a6e248a0118abe0a721ec62b51c.png

欢迎关注公众号:嵌入式学习与实践

猜你喜欢

转载自blog.csdn.net/weixin_46158019/article/details/133367333