Search code examples
clinuxlibc

Portable alternative to execvpe


The execvpe function is a GNU extension. If I want my code to e portable to non-gnu libcs, how can I change an execvpe call to be portable?

execvp doesn't set the environment of the new program, and execle poth doesn't allow passing an array as the argument and doesn't try to resolve the executable from PATH.


Solution

  • Change environ directly.

    Per the POSIX exec() documentation (bolding mine):

    ... In addition, the following variable, which must be declared by the user if it is to be used directly:

    extern char **environ;
    

    is initialized as a pointer to an array of character pointers to the environment strings. The argv and environ arrays are each terminated by a null pointer. The null pointer terminating the argv array is not counted in argc.

    Applications can change the entire environment in a single operation by assigning the environ variable to point to an array of character pointers to the new environment strings. ...

    So instead of

    exec...e( ...., myNewEnv );
    

    you can do

    extern char **environ;
    
       .
       .
       .
    
    environ = myNewEnv;
    exec...(...);