学习啦>学习电脑>操作系统>Linux教程>

linux system函数

时间: 佳洲1085 分享

  system()函数是Linux下的一个函数,那么它具体作用是干什么呢?下面由学习啦小编为大家整理了linux system()函数的相关知识,希望对大家有帮助!

  一,linux system()函数理解

学习啦在线学习网   功能:system()函数调用“/bin/sh -c command”执行特定的命令,阻塞当前进程直到command命令执行完毕

  原型:

学习啦在线学习网   int system(const char *command);

  返回值:

学习啦在线学习网   如果无法启动shell运行命令,system将返回127;出现不能执行system调用的其他错误时返回-1。如果system能够顺利执行,返回那个命令的退出码。

  说明:

  man帮助:

  #include

  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.

学习啦在线学习网   RETURN VALUE

学习啦在线学习网   The value returned is -1 on error (e.g. fork(2) failed), and the

  return status of the command otherwise. This latter return status is

  in the format specified in wait(2). Thus, the exit code of the command

学习啦在线学习网   will be WEXITSTATUS(status). In case /bin/sh could not be executed,

  the exit status will be that of a command that does exit(127).

学习啦在线学习网   If the value of command is NULL, system() returns non-zero if the shell

  is available, and zero if not.

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

  二,linux system()函数原理

学习啦在线学习网   system函数执行时,会调用fork、execve、waitpid等函数。

学习啦在线学习网   linux版system函数的源码:

  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;

  }

  三,linux system()函数说明

  system()会调用fork()产生子进程,由子进程来调用/bin/sh-c string来执行参数string字符串所代表的命令,此命>令执行完后随即返回原调用的进程。

  在调用system()期间SIGCHLD 信号会被暂时搁置,SIGINT和SIGQUIT 信号则会被忽略。

  返回值

学习啦在线学习网   =-1:出现错误

  =0:调用成功但是没有出现子进程

  >0:成功退出的子进程的id

  如果system()在调用/bin/sh时失败则返回127,其他失败原因返回-1。若参数string为空指针(NULL),则返回非零值>。如果system()调用成功则最后会返回

  执行shell命令后的返回值,但是此返回值也有可能为 system()调用/bin/sh失败所返回的127,因此最好能再检查errno 来确认执行成功。

  附加说明

  在编写具有SUID/SGID权限的程序时请勿使用system(),system()会继承环境变量,通过环境变量可能会造成系统安全的问题。

  system函数对返回值的处理,涉及3个阶段:

学习啦在线学习网   阶段1:创建子进程等准备工作。如果失败,返回-1。

  阶段2:调用/bin/sh拉起shell脚本,如果拉起失败或者shell未正常执行结束(参见备注1),原因值被写入到status的低8~15比特位中。system的man中只说明了会写了127这个值,但实测发现还会写126等值。

学习啦在线学习网   阶段3:如果shell脚本正常执行结束,将shell返回值填到status的低8~15比特位中。

3582371