我的 C++ 程序中有一个函数,如下所示:
std::string SysExec::executeAndReturnResult(char* cmd) {
//cout << "[SHELL] : " << cmd << endl;
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;
}
当我调用它时
SysExec::executeAndReturnResult("/usr/bin/irsend -d /var/run/lirc/lircd-lirc0 SEND_ONCE Samsung 4");
我明白了:
sh: 4: not found
但是,如果我尝试从控制台执行相同的命令,它工作正常。
我想提一下,使用非数字参数调用它没有问题 - 以下工作正常:
SysExec::executeAndReturnResult("irsend -d /var/run/lirc/lircd-lirc0 SEND_ONCE Samsung channel+")
我试过谷歌..但无济于事。谁能帮我理解这个问题?
//根据要求编辑:
我的 SysExec.h 文件如下所示:
#include "CompileFlags.h"
/*
* sysexec.h
*
* Created on: Dec 19, 2012
* Author: Shrouk H. Khan / Fingi / root
*/
#ifndef SYSEXEC_H_
#define SYSEXEC_H_
#include<stdio.h>
#include <string>
#include <boost/algorithm/string.hpp>
namespace fingigcc {
class SysExec {
public:
SysExec();
virtual ~SysExec();
static std::string executeAndReturnResult(char* cmd);
static int executeAndForget(char* cmd);
static int execute(char* cmd);
};
} /* namespace fingigcc */
#endif /* SYSEXEC_H_ */
对应的 cpp 文件如下所示:
/*
* SysExec.cpp
*
* Created on: Dec 19, 2012
* Author: Shrouk H. Khan / Fingi / root
*/
#include "../../includes/SysExec.h"
#include "../../includes/Logger.h"
#include <cstdlib>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
namespace fingigcc {
SysExec::SysExec() {
// TODO Auto-generated constructor stub
}
SysExec::~SysExec() {
// TODO Auto-generated destructor stub
}
std::string SysExec::executeAndReturnResult(char* cmd) {
//cout << "[SHELL] : " << cmd << endl;
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;
}
int SysExec::executeAndForget(char* cmd) {
//cout << "[SHELL] : " << cmd << endl;
//do not try to log it..infinite loop..
// pid_t pid = fork();
// if (pid < 0) {
// return -1;
// } else if (pid == 0) {
// execl(cmd, (char *) 0);
// } else {
//
// }
system(cmd);
return 0;
}
}
/* namespace fingigcc */