【问题标题】:Using execl to copy two files provided when calling the executable使用 execl 复制调用可执行文件时提供的两个文件
【发布时间】:2016-05-09 02:35:42
【问题描述】:

我的可执行文件名为copy

我想要的时候执行

copy file1 file2

基本上做

cp -i -p file1 file2

我想使用execl 函数来完成此操作。

现在我对自动搜索命令路径的execvp 有了更多的专业知识。

所以我可以执行以下操作:

char *cmd[] = {"cp","-ip",0}
execvp(cmd[0],cmd);

但是我怎么能使用execvp 来指定argv[1] 是file1 和argv[2] 这是file2

【问题讨论】:

    标签: c process operating-system command exec


    【解决方案1】:

    这里是execl函数的原型:

    int execl(const char *path, const char *arg, ...
                           /* (char  *) NULL */);
    

    所以它接受二进制文件路径的参数,然后是参数。 您要使用的二进制文件是 cp,因此,路径将为 /bin/cp(您可以使用 whereis cp 找到二进制位置)。

    然后你只需要传递 cp 所需的参数。 比如这样:

    int main(int argc, char **argv)
    {
      execl("/bin/cp", "-i", "-p", argv[1], argv[2], (char *)0);
    }
    

    要获得 cp 交互式提示,您必须从 shell 调用 cp。为了模拟这一点,您可以使用 sh 调用您的命令。可以直接使用system函数,也可以使用execl家族的函数。

    int main(int argc, char **argv)
    {
      char *cmd;
      if (asprintf(&cmd, "cp -ip %s %s", argv[1], argv[2]) == -1)
        return (1);
      execlp("sh", "sh", "-c" , cmd, (char *)0);
    }
    

    【讨论】:

    • 你能把 -i 和 -p 组合成 -ip 吗??
    • 是的,您只需像在您的 unix shell 中一样提供参数。只需删除我示例中的“-p”,并将“-i”修改为“-ip”。 execvp也是一样,只是把args放在一个char *[]里面。 char *cmd[] = {"-ip", argv[1], argv[2], (char *)0};
    • 我有 char *copy[] = {"/bin/cp","-i","-p"}; execl(copy[0],copy[1],copy[2],argv[1],argv[2],(char *) 0);
    • 但它似乎并没有提示我过度写作,比如 -i 不起作用,你知道为什么@Louis
    • 这可能是因为您没有从 tty 执行它。所以它不会显示提示。但这只是一个假设。
    猜你喜欢
    • 2018-11-28
    • 1970-01-01
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多