我知道我迟到了,但是您可以本着 Foo 大师的“不编码获得优势”的精神在这里玩一个肮脏的把戏。和C 库函数实际上为您搜索 PATHexeclp()变量execvp()。execvpe()您所要做的就是在环境中将 PATH 替换为您的 THEPATH。它也使你的 shell 更安全,因为你所有的子进程都将使用你原来的 THEPATH 作为 PATH。
int i_path = -1;
int i_thepath = -1;
int i = 0;
while (envp[i] != NULL) {
if (strstr(envp[i], "PATH=") == envp[i])
i_path = i;
if (strstr(envp[i], "THEPATH=") == envp[i])
i_thepath = i;
i++;
}
if (i_path >= 0 && i_thepath >= 0)
envp[i_path] = envp[i_thepath] + 3; /* discard 'THE' */
else if (i_thepath >= 0)
envp[i_thepath] = envp[i_thepath] + 3; /* discard 'THE' */
execvpe(command, argv, envp);
如果您手动解析 THEPATH,请不要创建目录列表。在像 Perl 这样的高级语言中这很容易,但在 C 中涉及手动动态内存分配,因为您事先不知道 THEPATH 中有多少 dir 元素。要进行内存分配,您需要先遍历字符串。但是你可以在第一次迭代中完成真正的工作,使用strtok()with":"作为分隔符。
char *thepath = envp[i_thepath];
char *dir;
strtok(thepath, "="); /* first discard 'THEPATH=' */
while (dir = strtok(NULL, ":") {
/* now check if dir+command exists and is execuatble, exec */
}