我正在尝试解析命令行参数另一个程序(这是一个模拟器)在我的程序中使用system()
命令和模拟器的pid
。不幸的是同时使用文件读取和cat
,输出格式不正确,所以我无法真正获取数据。cat
在命令行上显示删除了空格的文件内容,整个字符串粘在一起,并使用ifstream
,它只显示程序的名称(我猜是第一个参数)。有人有什么想法吗?
参数的格式如下:
sudo ./src/yse6 -w -f tracefiles/capacity.3Mbps_400RTT_PER_0.0001.txt -at=eth1 -an=eth0
最终我需要显示与上面格式相同的字符串。
这是我到目前为止所做的:(ExecCommand()
获取命令,在命令行中运行它并返回结果string
. Secondary()
尝试使用文件读取器获取文件内容。)
std::string ExeCommand(const char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
void secondary(string addr){
ifstream file(addr.c_str(),ios::in);
if (file.good())
{
string str;
while(getline(file, str))
{
istringstream ss(str);
cout<<str<<endl;
char num[50];
while(ss >> num)
{
cout<<num;
}
}
}else{
cout<<"no file exists."<<endl;
}
}
int main (int argc, char* argv[])
{
if ((string) argv[1] == "-q") {
string pid=ExeCommand("ps -A | grep 'yse6' | awk '{print $1}'");
if(pid==""){
cout<<"No YSE emulator is running."<<endl;
}else{
pid=pid.substr(0,pid.size()-1);
cout<<pid<<endl;
string addr="cat /usr/bin/strings /proc/"+pid+"/cmdline";
cout<<addr<<endl;
// secondary(addr);
const char * c = addr.c_str();
string config=ExeCommand(c);
//get the config
cout << config<<endl;
}//end of else
}
}
像这样的东西,但有更多的错误检查,应该是一个好的开始(这比 C++ 更多的是 C,除了cout
bit):
const int BUFSIZE = 4096; // should really get PAGESIZE or something instead...
unsigned char buffer[BUFSIZE]; // dynamic allocation rather than stack/global would be better
int fd = open("/proc/self/cmdline", O_RDONLY);
int nbytesread = read(fd, buffer, BUFSIZE);
unsigned char *end = buffer + nbytesread;
for (unsigned char *p = buffer; p < end; /**/)
{ cout << p << endl;
while (*p++); // skip until start of next 0-terminated section
}
close(fd);
尤其,open()
and read()
应该检查错误条件,但我没有显示该部分...在命令行长度 > 4096 个字符的极端情况下,或者如果由于某种其他原因,这也可能会失败,read()
不会在一次调用中读取文件,这不应在当前调用中发生/proc
实现,但并不总是保证......
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)