Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a program make a system call to get the value of an environment variable in linux?

Or is it a function call? i know system calls are calls to a subroutine build in the system while function calls are calls within the program.

like image 878
j.gillis Avatar asked Oct 07 '17 17:10

j.gillis


1 Answers

No system call is done when reading environment variables.

On the C API level, the environment variables are passed to main as the third argument. The complete prototype is:

int main(int argc, char *argv[], char *envp[])

If you define your main this way, you will not even need function call to read the environment.

The following program prints all of your environment variables:

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char *argv[], char *envp[]) {
    while( *envp ) {
        printf("%s\n", *envp);
        envp++;
    }

    return 0;
}

Of course, main is just something invented by your compiler's runtime support libraries. As far as the OS is concerned, the interface is somewhat different. The same principle still stands, however. The environment is passed to the newly created program after execve on its stack.

This is also why getenv returns a char *. It does not need to allocate anything. It already has the string.

Edited to add: It is quite simple to know whether any specific function results in a system call or not (and which). All you have to do is run strace over the code. strace traps all (and only) system calls. If your getenv function call is invisible to it, it is not a system call.

like image 67
Shachar Shemesh Avatar answered Oct 20 '22 07:10

Shachar Shemesh