0

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.

  • Present your [MCVE]. We have no idea what your input is or where the target is on your system! Are `args[0]`, `args` and `env` what you expected them to be? #debugging – Lightness Races in Orbit Feb 15 '17 at 10:53
  • 3
    _No such file or directory._...... quite clear.....wrong path to file? – LPs Feb 15 '17 at 10:58
  • That does make sense, but shouldn't the env (environment variable) parameter to the execve() function contain the path of ls in its PATH variable? – Brandon Busby Feb 15 '17 at 11:02
  • 2
    You might try to use `execvpe()` to use the PATH environment variable – Ctx Feb 15 '17 at 11:03
  • Well, that was a simple fix. Thanks! – Brandon Busby Feb 15 '17 at 11:05
  • One more thing (since you emphasize, that the `env`-parameter contains the path-variable): This value will _not_ be used by `execvpe()` and friends, but the value of the _current_ environment of the process. – Ctx Feb 15 '17 at 11:28

0 Answers0