system() 执行 shell 命令
来源:互联网 发布:手机号小号软件 编辑:程序博客网 时间:2024/04/24 01:05
实现原理
strace 跟踪结果:
clone(child_stack=0, flags=CLONE_PARENT_SETTID|SIGCHLD, parent_tidptr=0x7fff936fc388) = 15661wait4(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
0 0
- system() 执行 shell 命令
- system(执行shell 命令)
- Python 执行shell命令:system
- php执行shell命令,system、exec、passthru
- linux C 语言的 system(执行shell 命令)
- python使用os.system执行Linux shell命令
- linux C 语言的 system(执行shell 命令)
- 执行shell命令的popen和system函数封装
- 服务端用system()执行shell命令获取执行结果(排除signal影响)
- C#执行Shell命令
- C#执行Shell命令
- SHELL 如何执行命令
- python执行shell命令
- C#执行Shell命令
- Android执行shell命令
- Android执行shell命令
- shell命令执行顺序
- Shell如何执行命令
- 如何用th:attr标签在thymeleaf模板中设置属性-原标题:How To Set Attributes in Thymeleaf Template using th:attr?
- 基本排序算法——选择,插入,冒泡
- OpenStack Liberty版本里如何配置基于haproxy的负载均衡服务(LBaaS)
- android集成支付,支付宝,微信
- [转载]offsetof与container_of宏
- system() 执行 shell 命令
- Visual Studio 2015更改背景与背景图
- android学习摘记——TabHost使用代码
- Assembly x64 Intro - SSE2 4x8 Store
- 关于java空指针一些心得体会
- java hashcode
- GitHub 优秀的 Android 开源项目
- SSH登陆远程主机后进入指定目录或执行命令
- 短信加密机制的设计模式