System函数返回值 和popen
#include <stdlib.h>
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.
int system(const char * cmdstring)
{
pid_t pid;
int status;
if(cmdstring == NULL)
{
return (1); //如果cmdstring为空,返回非零值,一般为1
}
if((pid = fork())<0)
{
status = -1; //fork失败,返回-1
}
else if(pid == 0)
{
execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
_exit(127); // exec执行失败返回127,注意exec只在失败时才返回现在的进程,成功的话现在的进程就不存在啦~~
}
else //父进程
{
while(waitpid(pid, &status, 0) < 0)
{
if(errno != EINTR)
{
status = -1; //如果waitpid被信号中断,则返回-1
break;
}
}
}
return status; //如果waitpid成功,则返回子进程的返回状态
}
仔细看完这个system()函数的简单实现,那么该函数的返回值就清晰了吧,那么什么时候system()函数返回0呢?只在command命令返回0时。
int status;
if(NULL == cmdstring) //如果cmdstring为空趁早闪退吧,尽管system()函数也能处理空指针
{
return XXX;
}
status = system(cmdstring);
if(status < 0)
{
printf("cmd: %s\t error: %s", cmdstring, strerror(errno)); // 这里务必要把errno信息输出或记入Log
return XXX;
}
if(WIFEXITED(status))
{
printf("normal termination, exit status = %d\n", WEXITSTATUS(status)); //取得cmdstring执行结果
}
else if(WIFSIGNALED(status))
{
printf("abnormal termination,signal number =%d\n", WTERMSIG(status)); //如果cmdstring被信号中断,取得信号值
}
else if(WIFSTOPPED(status))
{
printf("process stopped, signal number =%d\n", WSTOPSIG(status)); //如果cmdstring被信号暂停执行,取得信号值
}
到于取得子进程返回值的相关介绍可以参考另一篇文章:http://my.oschina.net/renhc/blog/35116
system()函数用起来很容易出错,返回值太多,而且返回值很容易跟command的返回值混淆。这里推荐使用popen()函数替代,关于popen()函数的简单使用也可以通过上面的链接查看。
popen()函数较于system()函数的优势在于使用简单,popen()函数只返回两个值:
成功返回子进程的status,使用WIFEXITED相关宏就可以取得command的返回结果;
失败返回-1,我们可以使用perro()函数或strerror()函数得到有用的错误信息。
这篇文章只涉及了system()函数的简单使用,还没有谈及SIGCHLD、SIGINT和SIGQUIT对system()函数的影响,事实上,之所以今天写这篇文章,是因为项目中因有人使用了system()函数而造成了很严重的事故。现像是system()函数执行时会产生一个错误:“No child processes”。
关于这个错误的分析,感兴趣的朋友可以看一下:http://my.oschina.net/renhc/blog/54582
=======================================================================================
APUE这本书,对system这个函数已经将的比较明白了,只是它的相关知识稍显分散。最开始我是去网上找的资料,自己写的测试代码,可是还是有很多迷惑的地方。后来才拿起APUE ,好好读了第八章和第十章的相关章节。
- #include <stdlib.h>
- int system(const char *command);
- 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).
- libin@libin:~/program/C/Linux/system$ ./tsys "nosuchcmd"
- sh: nosuchcmd: not found
- status = 32512
- normal termination,exit status = 127
- libin@libin:~/program/C/Linux/system$ ./tsys "ls /noexisted"
- ls: 无法访问/noexisted: 没有那个文件或目录
- status = 512
- normal termination,exit status = 2
- libin@libin:~/program/C/Linux/system$ ls /noexist
- ls: 无法访问/noexist: 没有那个文件或目录
- libin@libin:~/program/C/Linux/system$ echo $?
- 2
- libin@libin:~/program/C/Linux/system$
- Thus, the exit code of the command will be WEXITSTATUS(status)
- WIFEXITED(status) ! =0
- libin@libin:~/program/C/Linux/system$ stty -a
- speed 38400 baud; rows 36; columns 134; line = 0;
- intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = M-^?; eol2 = M-^?; swtch = M-^?; start = ^Q; stop = ^S;susp = ^Z;
- rprnt = ^R; werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
- -parenb -parodd cs8 hupcl -cstopb cread -clocal -crtscts
- -ignbrk brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff -iuclc ixany imaxbel iutf8
- opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
- isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt echoctl echoke
- libin@libin:~/program/C/Linux/system$ ./tsys "sleep 7"
- ^Cstatus = 2
- abnormal termination,signal number =2
- libin@libin:~/program/C/Linux/system$ sleep 7
- ^C
- libin@libin:~/program/C/Linux/system$ echo $?
- 130
- libin@libin:~/program/C/Linux/system$ ./tsys "sleep 7"
- ^\status = 3
- abnormal termination,signal number =3
- libin@libin:~/program/C/Linux/system$ sleep 7
- ^\退出
- libin@libin:~/program/C/Linux/system$ echo $?
- 131
- root@libin:~/program/C/Linux/system# ./tsys "sleep 50" &
- [1] 2518
- root@libin:~/program/C/Linux/system# ps -ef
- root 2359 2343 0 12:42 pts/0 00:00:00 /bin/bash
- root 2518 2359 0 12:55 pts/0 00:00:00 ./tsys sleep 50
- root 2519 2518 0 12:55 pts/0 00:00:00 sh -c sleep 50
- root 2520 2519 0 12:55 pts/0 00:00:00 sleep 50
- root 2521 2359 0 12:56 pts/0 00:00:00 ps -ef
- root@libin:~/program/C/Linux/system# kill -3 2520
- Quit
- status = 33536
- normal termination,exit status = 131
- root@libin:~/program/C/Linux/system# ./tsys "sleep 50" &
- [1] 2568
- root@libin:~/program/C/Linux/system# ps -ef
- root 2568 2359 0 13:01 pts/0 00:00:00 ./tsys sleep 50
- root 2569 2568 0 13:01 pts/0 00:00:00 sh -c sleep 50
- root 2570 2569 0 13:01 pts/0 00:00:00 sleep 50
- root 2571 2359 0 13:01 pts/0 00:00:00 ps -ef
- root@libin:~/program/C/Linux/system# kill -3 2569
- status = 3
- abnormal termination,signal number =3
- #define _XOPEN_SOURCE
- #include<stdio.h>
- #include<stdlib.h>
- #include<unistd.h>
- #include<signal.h>
- #include<sys/wait.h>
- void pr_exit(int status)
- {
- printf("status = %d\n",status);
- if(WIFEXITED(status))
- {
- printf("normal termination,exit status = %d\n",WEXITSTATUS(status));
- }
- else if(WIFSIGNALED(status))
- {
- printf("abnormal termination,signal number =%d%s\n",
- WTERMSIG(status),
- #ifdef WCOREDUMP
- WCOREDUMP(status)?"core file generated" : "");
- #else
- "");
- #endif
- }
- }
- int main(int argc,char* argv[])
- {
- int status;
- if(argc<2)
- {
- fprintf(stderr,"usage:tsys cmd\n");
- return -1;
- }
- if((status = system(argv[1]) )<0)
- {
- fprintf(stderr,"system error\n");
- return -2;
- }
- pr_exit(status);
- return 0;
- }
一,system()理解
功能: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()函数原理
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; }
- 函数说明
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比特位中。
备注1:
只要能够调用到/bin/sh,并且执行shell过程中没有被其他信号异常中断,都算正常结束。
比如:不管shell脚本中返回什么原因值,是0还是非0,都算正常执行结束。即使shell脚本不存在或没有执行权限,也都算正常执行结束。
如果shell脚本执行过程中被强制kill掉等情况则算异常结束。
如何判断阶段2中,shell脚本子进程是否正常执行结束呢?系统提供了宏:WIFEXITED(status)。如果WIFEXITED(status)为真,则说明正常结束。
如何取得阶段3中的shell返回值?你可以直接通过右移8bit来实现,但安全的做法是使用系统提供的宏:WEXITSTATUS(status)。
由于我们一般在shell脚本中会通过返回值判断本脚本是否正常执行,如果成功返回0,失败返回正数。
所以综上,判断一个system函数调用shell脚本是否正常结束的方法应该是如下3个条件同时成立:
(1)-1 != status
(2)WIFEXITED(status)为真
(3)0 == WEXITSTATUS(status)
注意:
根据以上分析,当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; }
结果: