I try to do some homework exercise about creating a process with execv in linux.
I need to take an input string from the user, and check if there is a program with same name on the machine.
I need to try to execute the given program string with the PATH variable directories
I have to use the execv function ONLY to execute the program.
The input seperated by space when the first word is the file of the program and the other words are the arguments.
And they also ask me to validate that the environment has passed to the execv.
How do i check that?
I found out that I need to use the environ
variable and fill it
I Have tried this so far:
#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);
}
//}
}
some inputs like 'ls' reply that the argv vector is empty.