system

int system(const char *command);
system() executes a command specified in command by calling /bin/sh -c command, and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.

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 nonzero if the shell is available, and zero if not.


为了更好的理解system()函数返回值,需要了解其执行过程,实际上system()函数执行了三步操作

  1. fork一个子进程;
  2. 在子进程中调用exec函数去执行command;
    . 在父进程中调用wait去等待子进程结束。
  • 对于fork失败,system()函数返回-1。

  • 如果exec执行成功,也即command顺利执行完毕,则返回command通过exit或return返回的值。(注意,command顺利执行不代表执行成功,比如command:”rm debuglog.txt”,不管文件存不存在该command都顺利执行了)

  • 如果exec执行失败,也即command没有顺利执行,比如被信号中断,或者command命令根本不存在,system()函数返回127.

  • 如果command为NULL,则system()函数返回非0值,一般为1.

更多参考: https://blog.csdn.net/frecon/article/details/79783536

posted @ 2020-02-21 08:19  friedCoder  阅读(259)  评论(0)    收藏  举报