| 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 argument list, one argument to a line, of the process |
| 15 |
given by PID. */ |
| 16 |
|
| 17 |
void print_process_arg_list (pid_t pid) |
| 18 |
{ |
| 19 |
int fd; |
| 20 |
char filename[24]; |
| 21 |
char arg_list[1024]; |
| 22 |
size_t length; |
| 23 |
char* next_arg; |
| 24 |
|
| 25 |
/* Generate the name of the cmdline file for the process. */ |
| 26 |
snprintf (filename, sizeof (filename), "/proc/%d/cmdline", (int) pid); |
| 27 |
/* Read the contents of the file. */ |
| 28 |
fd = open (filename, O_RDONLY); |
| 29 |
length = read (fd, arg_list, sizeof (arg_list)); |
| 30 |
close (fd); |
| 31 |
/* read does not NUL-terminate the buffer, so do it here. */ |
| 32 |
arg_list[length] = '\0'; |
| 33 |
|
| 34 |
/* Loop over arguments. Arguments are separated by NULs. */ |
| 35 |
next_arg = arg_list; |
| 36 |
while (next_arg < arg_list + length) { |
| 37 |
/* Print the argument. Each is NUL-terminated, so just treat it |
| 38 |
like an ordinary string. */ |
| 39 |
printf ("%s\n", next_arg); |
| 40 |
/* Advance to the next argument. Since each argument is |
| 41 |
NUL-terminated, strlen counts the length of the next argument, |
| 42 |
not the entire argument list. */ |
| 43 |
next_arg += strlen (next_arg) + 1; |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
int main (int argc, char* argv[]) |
| 48 |
{ |
| 49 |
pid_t pid = (pid_t) atoi (argv[1]); |
| 50 |
print_process_arg_list (pid); |
| 51 |
return 0; |
| 52 |
} |