Debian Codegraph @

listings/chapter-7/get-pid.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 <stdio.h>
8 #include <sys/types.h>
9 #include <unistd.h>
10
11 /* Returns the process id of the calling processes, as determined from
12 the /proc/self symlink. */
13
14 pid_t get_pid_from_proc_self ()
15 {
16 char target[32];
17 int pid;
18 /* Read the target of the symbolic link. */
19 readlink ("/proc/self", target, sizeof (target));
20 /* The target is a directory named for the process id. */
21 sscanf (target, "%d", &pid);
22 return (pid_t) pid;
23 }
24
25 int main ()
26 {
27 printf ("/proc/self reports process id %d\n",
28 (int) get_pid_from_proc_self ());
29 printf ("getpid() reports process id %d\n", (int) getpid ());
30 return 0;
31 }