Search notes:
/proc/self
/proc/self
is a symbolic link to the directory of the «querying»
process (like
/proc/$$
in a shell).
Because
readlink
(or
ls -ld
) spawns a new process,
/proc/self
cannot be used in a shell to determine the shell's
PID:
$ echo $$
6184
$ readlink /proc/self
7392
$ readlink /proc/self
7393
$ ls -ld /proc/self
lrwxrwxrwx 1 root root 0 Jan 16 07:35 /proc/self -> 7395
However, with a C program, it can be shown /proc/self
points to its own PID because the same process prints the PID and executes the readlink
syscall:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
printf("My PID %d\n", getpid());
char symlink_path[256];
ssize_t len = readlink("/proc/self", symlink_path, sizeof(symlink_path)-1);
if (len != -1) {
symlink_path[len] = '\0';
printf("proc/self -> %s\n", symlink_path);
} else {
perror("Failed to read the symlink");
}
return 0;
}
$ gcc pid-and-proc-self.c -o pid-and-proc-self
$ ./pid-and-proc-self
My PID 7847
proc/self -> 7847
See also
/proc/mounts
and
/proc/net
are somewhat special because they're symlinks to the respective files in
/proc/self
(see
/proc/self/mounts
).