Skip to content

Instantly share code, notes, and snippets.

@iwagaki
Created January 27, 2015 09:28
Show Gist options
  • Save iwagaki/ad0a9939f3d434cdeb89 to your computer and use it in GitHub Desktop.
Save iwagaki/ad0a9939f3d434cdeb89 to your computer and use it in GitHub Desktop.
Get a path name by a fd (file descriptor)
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define VERIFY(x) if (!(x)) { assert(x); abort(); }
int main(int argc, char *argv[])
{
pid_t pid = 0;
int fd = 0;
char proc_path[1024];
char path[1024];
VERIFY(argc == 2);
fd = open(argv[1], O_RDONLY);
pid = getpid();
sprintf(proc_path, "/proc/%d/fd/%d", (int)pid, fd);
int size = readlink(proc_path, path, 1024);
VERIFY(size > 0);
path[size] = 0; // for null-termination
printf("fd = %d, path = %s\n", fd, path);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment