一、系统命令system
1、示例:
#include <cstdlib> // 必须包含这个头文件来使用system()
int main() {
system("sleep 10"); // 塞执行
return 0;
}
- 程序会等待10秒后,执行完成
- 使用
system("sleep 10 &");
可以实现非阻塞执行
2、示例: 注意若用了分号;
,&
只对前面指令有效
#include <cstdlib> // 必须包含这个头文件来使用system()
int main() {
system("sleep 10; ls &"); // 非阻塞执行
return 0;
}
3、示例
#include <cstdlib> // 必须包含这个头文件来使用system()
int main() {
system("sleep 10 && ls &"); // 非阻塞执行
return 0;
}
二、系统命令获取返回值
popen示例一:保留’\n’
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
std::string execCmd(const char* cmd) {
FILE *pp = popen(cmd, "r");
char tmp[1024];
std::string result;
while (fgets(tmp, sizeof(tmp), pp) != NULL)
result += tmp;
pclose(pp);
return result;
}
int main() {
for (int i = 0; i < 10; ++i) {
std::string output = execCmd("ls");
std::cout << output;
}
return 0;
}
示例二:
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <cstring>
std::string execCmd(const char* cmd) {
FILE *pp = popen(cmd, "r");
char tmp[1024];
std::string result;
while (fgets(tmp, sizeof(tmp), pp) != NULL) {
// 去除换行符
size_t pos = strlen(tmp);
if (pos > 0 && tmp[pos - 1] == '\n') {
tmp[pos - 1] = '\0';
}
result += tmp;
}
pclose(pp);
return result;
}
int main() {
for (int i = 0; i < 10; ++i) {
std::string output = execCmd("pwd");
std::cout << output;
}
return 0;
}
示例三
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
int main() {
try {
std::string command = "cat 22/ZX_FourdDataStruct.h";
std::string output = exec(command.c_str());
std::cout << "Output:\n" << output << std::endl;
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}