如何从C ++程序运行bash脚本

时间:2009-03-14 16:43:08

标签: c++ linux bash shell

Bash脚本非常有用,可以节省大量的编程时间。那么如何在C ++程序中启动bash脚本呢?此外,如果你知道如何让用户成为超级用户也会很好。谢谢!

5 个答案:

答案 0 :(得分:60)

使用system功能。

system("myfile.sh"); // myfile.sh should be chmod +x

答案 1 :(得分:15)

#include <stdio.h>
#include <stdlib.h>

// ....


system("my_bash_script.sh");

答案 2 :(得分:9)

唯一标准的强制实现依赖方式是使用system()中的stdlib.h函数。

  

此外,如果您知道如何让用户成为超级用户也会很好。

您希望脚本以超级用户身份运行,还是希望提升C可执行文件的权限?前者可以使用sudo完成,但在使用sudo之前,您需要了解一些事项。

答案 3 :(得分:4)

StackOverflow: How to execute a command and get output of command within C++?

StackOverflow: (Using fork,pipe,select): ...nobody does things the hard way any more...

  
    

此外,如果你知道如何让用户成为超级用户也会很好。谢谢!

  

须藤。苏。 chmod 04500.(setuid()&amp; seteuid(),但它们要求你已经是root .E..g.chmod'ed 04 ***。)

保重。这些可以打开“有趣的”安全漏洞......

根据您的操作,您可能不需要root。 (例如:我经常 chmod / chown / dev 设备(串口等)(在 sudo root 下)所以我可以从我的软件中使用它们而不是root另一方面,在加载/卸载内核模块时,这种方法效果不佳......)

答案 4 :(得分:2)

Since this is a pretty old question, and this method hasn't been added (aside from the system() call function) I guess it would be useful to include creating the shell script with the C binary itself. The shell code will be housed inside the file.c source file. Here is an example of code:

#include <stdio.h>
#include <stdlib.h>

#define SHELLSCRIPT "\
#/bin/bash \n\
echo -e \"\" \n\
echo -e \"This is a test shell script inside C code!!\" \n\
read -p \"press <enter> to continue\" \n\
clear\
"

int main() {

system(SHELLSCRIPT);
return 0;
}

Basically, in a nutshell (pun intended), we are defining the script name, fleshing out the script, enclosing them in double quotes (while inserting proper escapes to ignore double quotes in the shell code), and then calling that script's name, which in this example is SHELLSCRIPT using the system() function in main().