Linux之system函数--在程序中执行命令

来源:互联网 发布:微霸科技软件 编辑:程序博客网 时间:2024/05/29 17:13
NAME
       system - execute a shell command

SYNOPSIS
       #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);

(其实就是使用fork创建一个sh进程,然后将命令传递给sh进程执行命令,注意这里要加一个“-c”选项,不然不能执行可执行命令而只能执行脚本命令。其实我自己也这样用过,但是不是使用sh来执行命令,而是直接把可执行程序用execl函数加载执行,这样也可以实现类似的功能,但是不能执行脚本文件/文件,因为脚本命令不是可执行文件,脚本文件是使用sh解析执行的。


       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  avail‐
       able 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 termination  status  of  the
          child shell used to execute command.  (The termination status of a shell is the termi‐
          nation status of the last command 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.