system() 执行 shell 命令
2015-12-16 15:11
381 查看
实现原理
strace 跟踪结果:clone(child_stack=0, flags=CLONE_PARENT_SETTID|SIGCHLD, parent_tidptr=0x7fff936fc388) = 15661 wait4(15661, [{WIFEXITED(s) && WEXITSTATUS(s) == 0}], 0, NULL) = 15661实际的过程:
1. 父进程 - clone() 一个子进程
2. 父进程 - wait4() 子进程退出(如果 SIGCHLD 处理方式为 SIG_DFL, 则阻塞等待指子进程退出;如果是 SIG_IGN, 则立马返回 -1)
3. 子进程 - execl(/bin/sh -c command)
返回值
返回值可能的情况:-1: system() 执行失败,例如 clone() 失败、wait4() 失败(SIG_IGN 时返回 -1)
>=0: system() 执行成功,命令执行成功或失败,通过 WEXITSTATUS() 获取命令执行的返回码
正确的使用方法
1. 处理 SIGCHLD 信号2. WIFEXITED() 和 WEXITSTATUS()
#include <errno.h> #include <string.h> #include <stdlib.h> #include <signal.h> #include <string> #include <iostream> int main(int argc, char* argv[]) { char cmd[] = "su www -c 'kdir -p -m 755 /data/inst-123456 &>/dev/null '"; sighandler_t old_sighandler = signal(SIGCHLD, SIG_DFL); int rv = system(cmd); signal(SIGCHLD, old_sighandler); if (-1 == rv) { std::cout << "error: " << strerror(errno) << std::endl; return -1; } std::cout << "return value: " << rv << std::endl; if (WIFEXITED(rv)) { std::cout << "subprocess exited, exit code: " << WEXITSTATUS(rv) << std::endl; if (0 == WEXITSTATUS(rv)) { // if command returning 0 means succeed std::cout << "command succeed" << std::endl; } else { if(127 == WEXITSTATUS(rv)) { std::cout << "command not found" << std::endl; return WEXITSTATUS(rv); } else { std::cout << "command failed: " << strerror(WEXITSTATUS(rv)) << std::endl; return WEXITSTATUS(rv); } } } else { std::cout << "subprocess exit failed" << std::endl; return -1; } return 0; }
命令后台执行
如果想命令在后台执行,可以在命令后面加 "&", 但是这样做的后果是:只要 system() 执行成功,不管命令是否存在、命令执行是否成功,返回值都为 0.popen
http://blog.csdn.net/duyiwuer2009/article/details/50688493相关文章推荐
- shell的时间定义
- zeus之shell基本命令
- shell的foreach 函数
- bash下. : () {} [] [[]] (())的解释
- Shell脚本利用gnuplot绘制图片
- Linux Shell脚本实现根据进程名杀死进程
- 万能五笔输入法导致vs2013 xshell中文乱码
- shell中的exec命令
- shell 执行jar 的命令
- shell中 括号的作用
- shell脚本中select的应用
- Bash Shell:变量总结
- githup中shell命令的常见错误
- Linux基础8 bash的特性
- shell学习--控制结构
- linux shell 之sed命令
- 【随笔】Linux & Shell & Minecraft
- powershell 判断操作系统版本 命令
- xshell配色方案
- [转]adb shell dumpsys 命令