Debian Codegraph @

listings/chapter-7/print-environment.c

raw
1 /***********************************************************************
2 * Code listing from "Advanced Linux Programming," by CodeSourcery LLC *
3 * Copyright (C) 2001 by New Riders Publishing *
4 * See COPYRIGHT for license information. *
5 ***********************************************************************/
6
7 #include <fcntl.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <sys/stat.h>
11 #include <sys/types.h>
12 #include <unistd.h>
13
14 /* Prints the environment, one environment variable to a line, of the
15 process given by PID. */
16
17 void print_process_environment (pid_t pid)
18 {
19 int fd;
20 char filename[24];
21 char environment[8192];
22 size_t length;
23 char* next_var;
24
25 /* Generate the name of the environ file for the process. */
26 snprintf (filename, sizeof (filename), "/proc/%d/environ", (int) pid);
27 /* Read the contents of the file. */
28 fd = open (filename, O_RDONLY);
29 length = read (fd, environment, sizeof (environment));
30 close (fd);
31 /* read does not NUL-terminate the buffer, so do it here. */
32 environment[length] = '\0';
33
34 /* Loop over variables. Variables are separated by NULs. */
35 next_var = environment;
36 while (next_var < environment + length) {
37 /* Print the variable. Each is NUL-terminated, so just treat it
38 like an ordinary string. */
39 printf ("%s\n", next_var);
40 /* Advance to the next variable. Since each variable is
41 NUL-terminated, strlen counts the length of the next variable,
42 not the entire variable list. */
43 next_var += strlen (next_var) + 1;
44 }
45 }
46
47 int main (int argc, char* argv[])
48 {
49 pid_t pid = (pid_t) atoi (argv[1]);
50 print_process_environment (pid);
51 return 0;
52 }