功能:system()函數調用“/bin/sh -c command”執行特定的命令,阻塞當前進程直到command命令執行完畢
原型:
int system(const char *command);
返回值:
如果無法啟動shell運行命令,system將返回127;出現不能執行system調用的其他錯誤時返回-1。如果system能夠順利執行,返回那個命令的退出碼。
說明:
man幫助:
#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.
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.
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;
}
函數說明
返回值
>0
:成功退出的子進程的id附加說明
system函數對返回值的處理,涉及3個階段:
備註1:
由於我們一般在shell腳本中會通過返回值判斷本腳本是否正常執行,如果成功返回0,失敗返回正數。 所以綜上,判斷一個system函數調用shell腳本是否正常結束的方法應該是如下3個條件同時成立:
注意: 根據以上分析,當shell腳本不存在、沒有執行權限等場景下時,以上前2個條件仍會成立,此時WEXITSTATUS(status)為127,126等數值。 所以,我們在shell腳本中不能將127,126等數值定義為返回值,否則無法區分中是shell的返回值,還是調用shell腳本異常的原因值。shell腳本中的返回值最好多1開始遞增。
示例程序:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define EXIT_ERR(m) \
do\
{\
perror(m);\
exit(EXIT_FAILURE);\
}\
while (0);\
int main(void)
{
int status ;
status = system("ls -l|wc -l");
if(status == -1){
EXIT_ERR("system error");
}
else{
if(WIFEXITED(status))
{
if(WEXITSTATUS(status) == 0)
printf("run command successful\n");
else
printf("run command fail and exit code is %d\n",WEXITSTATUS(status));
}
else
printf("exit status = %d\n",WEXITSTATUS(status));
}
return 0;
}
結果: