3

I read cat /proc/[pid]/maps gives the informaion about its address space. So I want to write a program which will print its own address space.

My program is this;

  pid_t pid;
  int fd;
  char *buf;

  pid = getpid();

  fd = open("/proc/????/maps", O_RDONLY);

I'm getting the PID, but it won't help me to open the file. How to convert the pid from pid_t to string and add it to open call?

Or is there any other way to open the file?

imp25
  • 2,327
  • 16
  • 23
gangadhars
  • 2,584
  • 7
  • 41
  • 68

2 Answers2

9

All modern procfs systems implement "/proc/self/" for the running process. Just

fd = open("/proc/self/maps", O_RDONLY);

If you still wish to create the path string yourself then you have to use sprintf

char filename[128];
sprintf(filename, "/proc/%d/maps", getpid());
fd = open(filename, O_RDONLY);
Sergey L.
  • 21,822
  • 5
  • 49
  • 75
  • but i want to use only API's – gangadhars Oct 24 '13 at 14:17
  • @SGG I don't get that question. What APIs do you want to use? – Sergey L. Oct 24 '13 at 14:18
  • 1
    sprintf is c funcion. Is there any API for that? – gangadhars Oct 24 '13 at 14:22
  • @SGG - what's your idea of an API? Stick the above code in a function, add some error checking, and shazaam, you have an API. – Duck Oct 24 '13 at 14:26
  • @SGG As I wrote above your easiest way is to just open `/proc/self/maps` which is a symlink to the calling processes `/proc/pid`. `sprintf` function is part of the C standard and is found in `stdio.h`. It will come with every `libc` which also contains `open` and the other functions you need to actually read that file. – Sergey L. Oct 24 '13 at 14:43
-1

If you just want to print mapping information for review, one simple method:

you can use system library call to execute cat /proc/[pid]/maps

A simple C code is as follows:

char command[256];
sprintf(command, "cat /proc/%d/maps", getpid());
system(command);

You can refer to one example in my Gist.

慕冬亮
  • 339
  • 1
  • 2
  • 10
  • This does not give anything the earlier comment did not have. Using system() is lazy and bad form. Being inefficient is least of its problems. It can be affected by number of outside factors causing unexpected behavior and side effects, including being more open for exploit. And unless you do it right, it can for example eat your SIGINT (Ctrl-C). – Marko Kohtala Mar 19 '21 at 15:25