从C ++执行shell命令时找不到sh

时间:2013-10-15 13:49:14

标签: c++ shell path pipe

我的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+") 

我试过Google ..但无济于事。任何人都可以帮我理解这个问题吗?

//按要求编辑:

我的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 */

0 个答案:

没有答案