我尝试做一些关于在 linux 中使用 execv 创建进程的家庭作业。我需要从用户那里获取一个输入字符串,并检查机器上是否有同名的程序。我需要尝试使用 PATH 变量目录执行给定的程序字符串,我必须仅使用 execv 函数来执行程序。当第一个单词是程序的文件,其他单词是参数时,输入以空格分隔。他们还要求我验证环境是否已传递给 execv。我该如何检查?我发现我需要使用environ
变量并填充它
到目前为止,我已经尝试过:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MYCOMMAND_LEN 1000
#define MYNUM_OF_PARAMS 500
extern char **environ;
int main()
{
int i = 0, j, pid, stat, amountOfLib;
char command[MYCOMMAND_LEN];
char *params[MYNUM_OF_PARAMS];
char *path, *lastStr;
char *libs[100];
int numberOflib = 0, numOfParams;
char *commandPath;
//cut path
path = getenv("PATH");
lastStr = strtok(path, ":");
libs[0] = (char*)malloc(sizeof(char)*strlen(lastStr) + 1);
strcpy(libs[0], lastStr);
i = 1;
while (lastStr = strtok(NULL, ":")) {
libs[i] = (char*)malloc(sizeof(char)*strlen(lastStr) + 1);
strcpy(libs[i], lastStr);
i++;
numberOflib = i;
}
numberOflib = i;
puts("Please Enter Command: ");
gets(commandPath);
//loop until leave {
while (strcmp(command, "leave") != 0) {
//cut command
lastStr = strtok(command, " ");
params[0] = (char*)malloc(sizeof(char)*(strlen(lastStr) + 1));
strcpy(params[0], lastStr);
i = 1;
while ((lastStr = strtok(NULL, " ")) != NULL)
{
params[i] = (char*)malloc(sizeof(char)*(strlen(lastStr) + 1));
strcpy(params[i], lastStr);
i++;
}
params[i] = NULL;
numOfParams = i;
//check if first is relative
if ((pid = fork()) == 0) {
if (params[0][0] == '/' ||
(strlen(params[0]) >= 2 &&
params[0][0] == '.' &&
params[0][1] == '/'
) ||
(strlen(params[0]) >= 3 &&
params[0][0] == '.' &&
params[0][1] == '.' &&
params[0][2] == '/'
)
) execv(params[0], params);
// if command like "man ls"
else {
for (i = 0; i < amountOfLib; i++) {
commandPath = libs[i];
strcat(commandPath, "/");
strcat(commandPath, params[0]);
for (j = 0; j < numOfParams; j++) {
environ[j] = params[j]; //last environ also get the null
}
execv(commandPath, NULL);
}
puts("command not found in PATH");
exit(1);
}
} else {
wait(&stat);
}
puts("Please Enter Command: ");
gets(commandPath);
}
//}
}
像“ls”这样的一些输入回复 argv 向量为空。