Ticket #3072: origin.c

File origin.c, 1.3 KB (added by duncan, 5 years ago)
Line 
1#include <unistd.h>
2#include <stdio.h>
3#include <string.h>
4#include <errno.h>
5
6extern char **environ;
7
8int main (int argc, char *argv[]) {
9 
10  // find the number of env entries
11  int n_env = 0;
12  while (environ[n_env] != 0) {
13    n_env++;
14  }
15  printf("%d env entries.\n", n_env);
16
17  char buf[100];
18  int size = 0;
19  int err = 0;
20
21  // print the /proc/self/exe symlink
22  size = readlink("/proc/self/exe", &buf[0], 100);
23  if (err != 0) printf("errno = %d\n", errno);
24  buf[size]=0;
25  printf("readlink %s\n", &buf[0]);
26
27  // Delete our own executable file
28  err = unlink(&buf[0]);
29  if (err != 0) printf("errno = %d\n", errno);
30
31  // Print the /proc/self/exe symlink again
32  size = readlink("/proc/self/exe", &buf[0], 100);
33  if (err != 0) printf("errno = %d\n", errno);
34  buf[size]=0;
35  printf("readlink %s\n", &buf[0]);
36
37  // Print the exe origin file as given us by the kernel. We find this
38  // after the environment block (hence having to find its size above)
39  //
40  // See http://lkml.org/lkml/2008/5/1/181
41  // Choice quote:
42  //   Those who want to use it dislike the expression
43  //     (char *)(1+ strlen(env[-1+ n_env]) + env[-1+ n_env])
44  //
45  char *origin = (char *)(1+ strlen(environ[-1+ n_env]) + environ[-1+ n_env]);
46  printf("origin = %s\n",origin);
47
48  return 0;
49}