- 论坛徽章:
- 0
|
本帖最后由 myfifi_cu 于 2014-01-27 16:14 编辑
与平台无关,执行系统脚本或者命令的代码:- // 执行系统命令,返回命令执行结果字符串
- string get_output_of_cmd(const string &cmd) {
- int32_t count(2048);
- char s[2048];
- string ret;
- FILE* stream = popen(cmd.c_str(), "r");
- if (stream != NULL) {
- // 每次从stream中读取指定大小的内容
- while (fgets(s, count, stream))
- ret += s;
- pclose(stream);
- }
- return ret;
- }
- // 执行系统命令,根据命令退出代码返回布尔值
- bool get_exit_status_of_cmd(const string &cmd) {
- return (system(cmd.c_str()) == 0);
- }
- 调用:
- get_output_of_cmd("ls /root");
- get_output_of_cmd("/data/test.sh");
- get_exit_status_of_cmd("ls /root");
- get_exit_status_of_cmd("/data/test.sh");
复制代码 |
|