-3

Im trying to use execve() with set variables, but i tried using getenv() and setting HOME at the start and it never works

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>

int main( ){
  char *args[] = { "ls",NULL};//, "-l", "/", NULL};
  char *environ[] = { getenv("PATH") , NULL };
  printf("Listing directory:\n");
  int ret = execve(args[0], args, environ);
  printf("shouldnt be here =  %d\n",ret);
  puts(getenv("PATH"));
  return EXIT_FAILURE;
}
Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
AGEERRTT
  • 7
  • 1
  • 2
    The explanation is very simple: `execve` does not use `PATH`. Additionally, your usage of `execve` is completely broken. The strings should be of the form "name=value", and you're specifying just "value". The child process, if it starts, will have a completely garbled environment. – Sam Varshavchik Aug 26 '23 at 19:30
  • char *environ[] = { "PATH=/bin" , NULL }; i tried the following and it still doesnt work. – AGEERRTT Aug 26 '23 at 19:34
  • 2
    Did you miss the part where I mentioned that `execve` does not use `PATH`? – Sam Varshavchik Aug 26 '23 at 19:36
  • The environment you pass to [`execve`](https://man7.org/linux/man-pages/man2/execve.2.html) is used for the program it executes, not for the call itself. And as mentioned, `execve` doesn't use the `PATH`. You probably want one of the [`exec`](https://man7.org/linux/man-pages/man3/exec.3.html) wrapper functions (like e.g. `execvp`, the `p` is because it *does* search the `PATH`). – Some programmer dude Aug 26 '23 at 19:39
  • how can it be set to read off /bin then? – AGEERRTT Aug 26 '23 at 19:39
  • Specify it: `/bin/ls`, `/bin/cat`, etc... – Sam Varshavchik Aug 26 '23 at 19:41
  • but thats specifying the full path to a program in the start of args[], im trying to implement any of the programs in bin – AGEERRTT Aug 26 '23 at 19:46
  • Then use one of the `exec*` functions with a `p` in it, like `execvpe`. You do have the `man` pages installed, right? – Ted Lyngmo Aug 26 '23 at 19:54
  • 1
    Note that `getenv("PATH")` returns a pointer to the data after the `=` sign — so "setting the environment" using the the value returned by `getenv()` does not set `PATH` at all. – Jonathan Leffler Aug 27 '23 at 06:05

0 Answers0