以下命令在我的嵌入式Linux(Beaglebone Black)上运行良好:
echo bone_pwm_P9_21 > /sys/devices/bone_capemgr.?/slots
但是,在使用此小型C ++程序时不是:
#include <stdlib.h>
#include <string>
int main {
system(std::string("echo bone_pwm_P9_21 > /sys/devices/bone_capemgr.?/slots").c_str());
return 0;
}
问题涉及'?'
用作通配符的问号。当std::string
传递给的中的问号system()
被替换为正常字符时,该system()
函数将完美地评估命令。
我尝试过的没有成功的解决方案:
?
为\?
?
为*
注意:正如πάνταῥεῖ所指出的那样,该system()
命令调用shell,当提供正确的通配符时,通常将进行扩展:*
。如果您希望控件分别进行每个system()
调用或基础外壳受到限制,则此答案更为合适。
原始答案:
也许您可以在调用之前使用wordexp来构造字符串system()
:
#include <string>
#include <vector>
#include <iostream>
#include <wordexp.h>
std::vector<std::string> expand_env(const std::string& var, int flags = 0)
{
std::vector<std::string> vars;
wordexp_t p;
if(!wordexp(var.c_str(), &p, flags))
{
if(p.we_wordc)
for(char** exp = p.we_wordv; *exp; ++exp)
vars.push_back(exp[0]);
wordfree(&p);
}
return vars;
}
int main()
{
for(auto&& s: expand_env("$HOME/*")) // <= Note the wildcard '*'
std::cout << s << '\n';
}
在您的特定情况下,您可能会使用以下内容:
int main()
{
std::vector<std::string> devices = expand_env("/sys/devices/bone_capemgr.*/slots");
for(std::vector<std::string>::size_type i = 0; i < devices.size(); ++i)
system(("echo bone_pwm_P9_21 > " + devices[i]).c_str());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句