shell - How to set the environment variable of child same as parent to use execve in C? -


i trying set environment of child process similar parent process , need fill array called envp string follows:

char *envp = malloc(sizeof(args) / sizeof(char *)); strcpy(envp[0], strcat("home=", getenv("home"))); envp[1] = strcat("path=", getenv("path")); envp[2] = strcat("tz=", getenv("tz")); envp[3] = strcat("user=", getenv("user")); envp[4] = strcat("logname=", getenv("logname")); envp[5] = 0; 

inside if(fork() ==0)

setenv("parent", cwd, 1); if((execve(args[0], &args[0], envp)) < 0 ){             perror(*args);             exit(exit_failure); } 

i'm doing because don't know values of these environment variables want copy parent variables in order use them in execve() replace child process! i'm using execve() instead of execvp() because want handle searching cwd before executing command , search directories of shell path name of cwd not found.

so question is: how set values of array in correct way? plus, misunderstanding concept?

i looked @ many posts here, it's obvious i'm lost! in advance,

you not allocating memory strings envp [x]is pointing to. instead trying strcat or strcpy constant or non-allocated strings no-no (your compiler has warned you)

the general concept is

  1. you need allocate memory array of pointers environment strings (you did that).
  2. you need allocate memory each of strings pointers point @ (you didn't that). note memory goes ownership of process environment in oss, cannot use local variables , may not free memory.
  3. you need save pointers retrieved (2) array positions allocated @ (1) (you did that)

your code should similar (example "home" only, length of envbuff might need adjusted/checked):

char envbuff [100];  strcpy (envbuff, "home="); strcat (envbuff, getenv ("home)); envp [0] = strdup (envbuff); 

strdupactually allocates memory uses, strcator simple assignment envp[0] don't - strcat assumes there enough room both original , appended part , memory writable, both not true in case.


Comments