給定cmd表示程式命令列引數的單個字串,如何獲取argv可以傳遞給posix_spawn或的字串陣列execve。
應適當處理各種形式的參考(和轉義引號)(結果呼叫應與 POSIX 兼容 shell 中的呼叫相同)。支持其他轉義字符將是可取的。示例:#1、#2、#3。
uj5u.com熱心網友回復:
正如 Shawn 評論的那樣,在 Linux 和其他 POSIXy 系統中,您可以使用wordexp(),它作為此類系統上標準 C 庫的一部分提供。例如,run.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"。這使您可以控制將執行的二進制檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/336497.html
上一篇:我是否正確應用了嚴格別名規則?
