I'm trying to perform a simple test using the exec() function by emulating a Linux shell. The test program should take in commands in the following form: cmd arg1 arg2 ... where cmd is the command and arg1, arg2, ... are the command line arguments. The exec() function will then call the program specified by cmd.
What I have tried is:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
char line[128];
char *args[30];
int main(int argc, char *argv[], char *env[])
{
// Read command and arguments with fmt: cmd arg1 arg2 ...
line[strcspn(fgets(line, 128, stdin), "\r\n")] = 0;
// Tokenize command for input to exec();
int i = 0;
args[i] = (char *)strtok(line, " ");
while(args[++i] = (char *)strtok(NULL, " "));
if(fork())
{ // Parent
int *status;
wait(status);
printf("Child exit status: %d\n", *status);
return 0;
}
// Child
int execRV = execve(args[0], args, env);
printf("execve return value: %d\n", execRV);
perror(NULL);
return 0;
}
When the above program is run, execve() returns the error value -1 and the output from perror() is: No such file or directory.
Running the program on the command line:
gcc -m32 [programName].c
a.out
ls
execve return value: -1
No such file or directory
Child exit status: 0
The main parameters argc and argv should not matter for this example. The env parameter, however, is the Linux environment variable, which contains the PATH variable.