要从C++程序运行bash脚本,您可以使用以下方法:
system()
函数:#include<iostream>
#include <cstdlib>
int main() {
std::cout << "Executing bash script..."<< std::endl;
int result = system("/path/to/your/script.sh");
if (result == 0) {
std::cout << "Script executed successfully."<< std::endl;
} else {
std::cout << "Script execution failed."<< std::endl;
}
return 0;
}
popen()
和pclose()
函数:#include<iostream>
#include <cstdio>
#include <cstdlib>
int main() {
std::cout << "Executing bash script..."<< std::endl;
FILE* pipe = popen("/path/to/your/script.sh", "r");
if (!pipe) {
std::cout << "Script execution failed."<< std::endl;
return 1;
}
char buffer[128];
while (fgets(buffer, sizeof(buffer), pipe) != NULL) {
std::cout<< buffer;
}
int result = pclose(pipe);
if (result == 0) {
std::cout << "Script executed successfully."<< std::endl;
} else {
std::cout << "Script execution failed."<< std::endl;
}
return 0;
}
请注意,这些方法都需要在C++程序中包含相应的头文件,并且需要确保您的系统上已经安装了bash。此外,您需要确保您的bash脚本具有执行权限。
领取专属 10元无门槛券
手把手带您无忧上云