【问题标题】:C++ system calls "SED"C++ 系统调用“SED”
【发布时间】:2013-04-19 17:57:49
【问题描述】:

我正在尝试使用 c++ 程序运行 sep 命令。当我编译下面的代码时,我收到argv[0]="sep"; 的警告,说明"deprecated conversion from string constant to âchar*â [-Wwrite-strings]." 当我运行下面的程序时,我得到 Exec Failed!每次从 execvp() 下面的行开始。

#include<iostream>
#include<string>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <fcntl.h>

using namespace std;

int main(int argc, char **argv){
    pid_t pid;
    int fail;

    argv[0] = "sep";

    int i=0;
    while(i < argc){
        cout<< i << ": " << argv[i] <<endl;
        i++;
    }

    if(argc < 5){
        cout<< "./upload -i -r <key> <source> <destination>" <<endl;
    }else{
        pid = fork();
        if(pid < 0){
            cout<<"Fork Failed!\n";
            exit(1);
        }else if(pid == 0){                 //if you are in the child process
            fail = execvp("scp", argv); //execute command, return -1 on fail
            cout<< "Exec Failed!\n";
            exit(1);
        }else{
            int status;
            waitpid(pid, &status, 0);   //wait for each pid
        }
    }
    return 0;
}

【问题讨论】:

  • 如果execvp 失败,您应该检查errno 出了什么问题。使用例如strerror 获取可打印字符串。
  • 不错,“没有这样的文件或目录。” ./upload -r -i NewKey.pem UploadFolder ubuntu@ec2-54-245-152-141.us-west-2.compute.amazonaws.com:uploaded 是我在 NewKey.pem 所在的命令行中运行的我的 AWS 服务器的文件,另外两个是源和目标。 sep -r -i key source destination 不在程序内时有效...
  • 即使你已经猜到了,argv[0] = "scp"; 这行还是有问题的;如果您的程序名称少于三个字母,这可能会出现段错误。仅供参考...
  • 好电话。我将构建一个新的数组调用 args 并将每个值 = 设置为 argv 除了 set args[0] = "scp"
  • 同样这样,用户不必指定标志。我可以强迫他们标记我想要的。

标签: c++ system-calls


【解决方案1】:

哇...错字了。

其中 argv[0] = "sep";

应该是“scp”

    char** args;

    args = new char*[argc+2]; //forcing 2 flags
    args[0] = "scp";
    args[1] = "-i";
    args[2] = "-r";
    args[3] = argv[1]; //key
    args[4] = argv[2]; //source
    args[5] = argv[3]; //destination

    execvp(args[0], args);

【讨论】:

  • 大声笑...我永远也想不通。我将删除我的答案,因为它偏离了真正的问题。
  • 真正的问题 = 我的胖手指:P
猜你喜欢
  • 2016-02-09
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多