netdata:readlink獲取檔案描述符對應的檔名
阿新 • • 發佈:2021-01-05
技術標籤:# C++
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <zconf.h>
typedef struct procfile {
char filename[FILENAME_MAX + 1];
int fd;
} procfile;
#define PROCFILE_INCREMENT_BUFFER 512
procfile *procfile_open(const char *filename) {
int fd = open(filename, O_RDONLY, 0666);
if(fd == -1) {
printf("(%s)%d: Cannot open file '%s'", __FUNCTION__ , __LINE__, filename);
return NULL;
}
procfile *ff = malloc(sizeof(procfile) + PROCFILE_INCREMENT_BUFFER);
ff->filename[0] = '\0';
ff->fd = fd;
return ff;
}
char *procfile_filename(procfile *ff) {
if(ff->filename[0]) return ff->filename; // filename != 00000000
char buffer[FILENAME_MAX + 1];
snprintf(buffer, FILENAME_MAX, "/proc/self/fd/%d", ff->fd);
ssize_t l = readlink(buffer, ff->filename, FILENAME_MAX);
if(l == - 1)
snprintf(ff->filename, FILENAME_MAX, "unknown filename for fd %d", ff->fd);
else
ff->filename[l] = '\0';
return ff->filename;
}
int main() {
char *filename = "/proc/stat";
procfile *ff = procfile_open(filename);
if(ff == NULL){
return 0;
}
procfile_filename(ff);
printf("fd(%d) ---> filename(%s)", ff->fd, ff->filename);
return 0;
}