1

I'm trying to find the environment variables of a currently running process.

Let the executable be test. What I'm doing:

./test // first run test

Inside the program I have a print statement doing getpid() which prints out the current process's pid when the executable starts executing.

Then using the pid printed out to the console, I do,

strings /proc/<pid>/environ

Now, is there any other way to specify the pid without explicitly writing it out first?

I saw in one of the videos that they specify the pid with a command like this:

seed@ubuntu:~/test$ strings /proc/$$/environ | grep LOGNAME
LOGNAME=seed

I didn't understand it quite correctly. Assuming test as the executable, I tried:

seed@ubuntu: ./test$ strings /proc/\$\$/environ | grep LOGNAME

But it returns:

bash: /test$: No such file or directory

What am I doing wrong?

OS: Seed Ubuntu 16.04 (32 bit) running on Virtual Box GCC Version: 5.4.0

Link to video

2

In the terminal session transcript,

seed@ubuntu:~/test$ strings /proc/$$/environ | grep LOGNAME

the seed@ubuntu:~/test$ part is just the user's prompt string - the actual command is

strings /proc/$$/environ | grep LOGNAME

Here, $$ (without backslashes) is the PID of the shell, as described in the Special parameters section of man bash:

 $      Expands  to  the  process ID of the shell.  In a () subshell, it
          expands to the process ID of the current  shell,  not  the  sub‐
          shell.

So this command returns the value of LOGNAME in the shell's environment - it's not really meant for examining the environment of a process invoked from the shell (although in general, the process will inherit the shell's environment).


Inside a C program, you can obtain the values of environment variables much more directly, using the getenv function:

GETENV(3)                  Linux Programmer's Manual                 GETENV(3)

NAME
       getenv, secure_getenv - get an environment variable

SYNOPSIS
       #include <stdlib.h>

       char *getenv(const char *name);

So for example

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

int main(void)
{
  char *envval;

  if((envval = getenv("LOGNAME")) != NULL) {
    printf("Value of LOGNAME is: %s\n", envval);
  }
  else {
    printf("LOGNAME not found in environment\n");
  }

  return 0;
}

such that

$ gcc -o getenv_test getenv_test.c

$ LOGNAME=foo ./getenv_test 
Value of LOGNAME is: foo

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.