5

I need to see a concrete example of how to specify the environment for execve() in a c program. In my class, we are writing a program that will utilize both standard LINUX executables and our own executables. Thus, the environment searching PATH will have to contain tokens for both types of executables. I cannot find a good example of how to specify the environment (third argument) for execve() as every article seems to suggest we use execvp() or *clp() or *cl(), etc., instead.

In my project, we must use execve().

Right now, I'm just trying to get execve() to work for a basic "ls" command so that I can get it to work later for any and all executables.

Here is a snippet of my experiment code:

else if(strcmp(tokens[0], "1") == 0) {
    char *args[] = {"ls", "-l", "-a", (char *)0};
    char *env_args[] = {"/bin", (char*)0};
    execve(args[0], args, env_args);
    printf("ERROR\n");
    }

Each time command "1" is entered in my shell, I see my error message. I suspect this is because of the way I am declaring env_args[].

Can someone show me a good example of how to implement execve() with a specified command searching environment?

William-H
  • 53
  • 1
  • 1
  • 4
  • [Here](http://linux.die.net/man/3/execve) is an example. – Eugene Sh. Apr 13 '15 at 21:41
  • 1
    You are trying to implement `execvp` in terms of `execve`. This is how `execvp` is already implemented, so [you can look at its source code](https://github.com/zerovm/glibc/blob/master/posix/execvp.c#L50). – that other guy Apr 13 '15 at 21:44

1 Answers1

3

here is the documentation on execve() function http://linux.die.net/man/2/execve

it says:

int execve(const char *filename, char *const argv[], char *const envp[]);

envp is an array of strings, conventionally of the form key=value, which are passed as environment to the new program.

but in your program env_args does not look like key=value

So probably you should define env_args by the following way:

char *env_args[] = {"PATH=/bin", (char*)0};

or just

char *env_args[] = { (char*)0 };
Community
  • 1
  • 1
Sandro
  • 2,707
  • 2
  • 20
  • 30
  • 2
    Thank You! This just about worked. I was having trouble understanding the difference between Paths and Environments. Got it up and running! – William-H Apr 13 '15 at 22:04