解析命令行参数字符串为posix_spawn/execve数组



给定单个字符串cmd表示程序命令行参数,如何获得字符串数组argv,该数组可以传递给posix_spawnexecve

应该适当地处理各种形式的引号(和转义引号)(结果调用应该与posix兼容的shell中相同)。支持其他转义字符是可取的。示例:#1,#2,#3。

正如Shawn所评论的,在Linux和其他POSIXy系统中,您可以使用wordxp(),它是这些系统上作为标准C库的一部分提供的。例如,运行.h:

#ifdef __cplusplus
extern "C" {
#endif
/* Execute binary 'bin' with arguments from string 'args';
'args' must not be NULL or empty.
Command substitution (`...` or $(...)$) is NOT performed.
If 'bin' is NULL or empty, the first token in 'args' is used.
Only returns if fails.  Return value:
-1: error in execv()/execvp(); see errno.
-2: out of memory. errno==ENOMEM.
-3: NULL or empty args.
-4: args contains a command substitution. errno==EINVAL.
-5: args has an illegal newline or | & ; < > ( ) { }. errno==EINVAL.
-6: shell syntax error. errno==EINVAL.
In all cases, you can use strerror(errno) for a descriptive string.
*/
int run(const char *bin, const char *args);
#ifdef __cplusplus
}
#endif

并编译下面的C源文件到你的C或c++程序或库中的目标文件:

#define  _XOPEN_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <wordexp.h>
#include <string.h>
#include <errno.h>
int run(const char *bin, const char *args)
{
/* Empty or NULL args is an invalid parameter. */
if (!args || !*args) {
errno = EINVAL;
return -3;
}
wordexp_t  w;
switch (wordexp(args, &w, WRDE_NOCMD)) {
case 0: break;  /* No error */
case WRDE_NOSPACE: errno = ENOMEM; return -2; 
case WRDE_CMDSUB:  errno = EINVAL; return -4;
case WRDE_BADCHAR: errno = EINVAL; return -5;
default:           errno = EINVAL; return -6;
}
if (w.we_wordc < 1) {
errno = EINVAL;
return -3;
}
if (!bin || !*bin)
bin = w.we_wordv[0];
if (!bin || !*bin) {
errno = ENOENT;
return -1;
}
/* Note: w.ve_wordv[w.we_wordc] == NULL, per POSIX. */
if (strchr(bin, '/'))
execv(bin, w.we_wordv);
else
execvp(bin, w.we_wordv);
return -1;
}

例如,run(NULL, "ls -laF $HOME");将列出当前用户主目录的内容。环境变量将被展开。

run("bash", "sh -c 'date && echo'");执行bash,argv[0]=="sh",argv[1]=="-c",argv[2]=="date && echo"。这可以让你控制将要执行的二进制文件。