使用 execv 和 shell exec 的问题

Posted

技术标签:

【中文标题】使用 execv 和 shell exec 的问题【英文标题】:Problems using execv and shell exec 【发布时间】:2014-10-16 12:09:35 【问题描述】:

我正在尝试使用 execv 系统调用从 C++ 触发一个进程。在我通过调用非交互式 shell 启动进程之前尝试获取用户环境之前,它工作得很好。

我基本上改变的是我的命令(对于这个例子,我使用了一个转储 argv[] 数组的 test.bin 文件)现在前缀为: /bin/sh -l -c "exec ./testbin testargv1 testargv2"

当我从另一个 shell 启动命令时,我得到了这个:

0: ./testbin 1:./testargv1 2:./testargv2

同时,当我通过 c++ 程序中的 execve 启动它时,我得到:

0: /bin/sh 1:-l 2:-c 3:执行./testbin testargv1 testargv2

在 c 中,我只是在执行以下操作:

char* exe = "/bin/sh";
char** params =  "/bin/sh","-l","-c","exec ./testbin testargv1 testargv2",0 ;

execv(exe,params);

就像从 execve 启动时,shell 在分叉之前不会重新排列 argv。

有人有什么提示吗?

【问题讨论】:

【参考方案1】:

您确定向我们展示了正确的代码吗?在我看来,你正在做这样的事情:

char* exe = "./testbin";
char** params =  "/bin/sh","-l","-c","exec ./testbin testargv1 testargv2",0 ;
execv(exe,params);

通常您会删除 exe 变量并像这样调用 execv

execv(params[0], params);

【讨论】:

不完全是这样,但问题确实出在我的非伪代码中,它传递了错误的可执行文件名称

以上是关于使用 execv 和 shell exec 的问题的主要内容,如果未能解决你的问题,请参考以下文章