gpt4 book ai didi

c - 在C中实现 `executeUsingPATH()`

转载 作者:行者123 更新时间:2023-11-30 21:26:57 24 4
gpt4 key购买 nike

我有一个问题,如下。有人可以向我解释一下吗?

考虑基于 Unix 的操作系统中使用的环境变量。一个常见的环境变量名为 PATH,命令解释器或 shell 使用它来标识要搜索的目录名称以查找可执行程序。例如,PATH 的典型值可能是 /Users/chris/bin:/usr/local/bin:/usr/bin:/bin:.,它提供用于搜索所需程序的以冒号分隔的目录列表。

编写一个名为 executeUsingPATH() 的 C99 函数,该函数接受要执行的程序的名称以及要传递给该程序的以 NULL 结尾的参数 vector 程序。所请求的程序可以仅使用其名称来指定,也可以使用绝对路径名或相对路径名来指定。

intexecuteUsingPATH(char *programName, char *arguments[]); 函数 executeUsingPATH() 应尝试执行每个中的 programName按顺序通过 PATH 提供的目录。如果找到并可以执行programNam(向其传递指定的程序参数),则该函数应等待其执行终止,然后返回已终止进程的退出状态。如果函数无法找到并执行 programName,那么它应该简单地返回整数 -1。 您的函数不应简单地调用名为 execvp() 的类似库函数.

我不知道如何实现它。

最佳答案

需要考虑的一件事是 PATH 可能包含空组件,表示当前目录。总而言之,您的作业相当简单 - 请参阅内嵌注释。

int executeUsingPATH(char *programName, char *arguments[])
{
switch (fork())
{ siginfo_t info;
case -1: return -1; // failure
case 0: break; // execute child below
default: waitid(P_ALL, 0, &info, WEXITED);
return info.si_status;
}
// the following is executed in the child process
char *path = getenv("PATH");
char pathname[PATH_MAX];
size_t n;
for (; ; )
{
n = strcspn(path, ":"); // calculate directory name length
strncpy(pathname, path, n); // copy directory name to pathname
path += n; // skip over directory name
if (n) pathname[n++] = '/'; // append '/' unless name is empty
strcpy(pathname+n, programName);// append name of a program
execv(pathname, arguments); // try to execute the program
if (!*path++) exit(-1); // failure if no more directories
}
}

关于c - 在C中实现 `executeUsingPATH()`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56981114/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com