[英]How do I use **environ from unistd.h to search for the right path?
Hi I'm trying to use execvp()
in conjunction with the **environ
variable to find the right path for a command the user puts in. 嗨,我正在尝试将execvp()
与**environ
变量结合使用,以找到用户所输入命令的正确路径。
The problem is I don't really understand how to do this. 问题是我不太了解如何执行此操作。 I know I could just attempt to open the command files to check if they exist but I don't understand how to get the paths I need to search from **environ
. 我知道我只能尝试打开命令文件以检查它们是否存在,但我不知道如何从**environ
获取需要搜索的路径。
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main(void) {
char *start, *end;
char ch;
char* path = getenv("PATH");
if (!path) {
fprintf(stderr, "could not get $PATH, exiting\n");
exit(EXIT_FAILURE);
}
start = path;
do {
end = strchr(start, ':');
if (!end) {
printf("%s\n", start);
} else {
ch = *end;
*end = '\0';
printf("%s\n", start);
*end = ch;
}
start = end + 1;
} while (end != NULL);
return 0;
}
This small program demonstrates how you can get separate paths from env[PATH]. 这个小程序演示了如何从env [PATH]获得单独的路径。
man execvp: 人execvp:
execvp() will duplicate the actions of the shell in searching for an executable file execvp()将在搜索可执行文件时复制外壳程序的动作
Thus, you don't have to use the **environ variable to find the right path for a command ; 因此,您不必使用** environ变量来找到命令的正确路径 ; execvp()
does it for you. execvp()
为您做到了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.