-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy path12_3.c
129 lines (114 loc) · 3.23 KB
/
12_3.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <ctype.h>
#include <pwd.h>
#include <stdlib.h>
#include <limits.h>
#include <stdlib.h>
#include <unistd.h>
#define MAXNAME 256
#define MAXLINE 4096
int handle_proc(const char *dir, const char *filepath);
int main(int argc, char *argv[])
{
char dirname[MAXNAME];
char filepath[MAXNAME];
DIR *dirp;
struct dirent *dir_entry;
if (argc != 2)
{
printf("usage: <filepath>\n");
exit(0);
}
strcpy(filepath, argv[1]);
if (geteuid() != 0)
{
printf("This program need root mode\n");
exit(0);
}
printf("Print what processions have opened the path %s:\n", filepath);
dirp = opendir("/proc");
if (dirp == NULL)
{
printf("opendir failed\n");
exit(1);
}
while ((dir_entry = readdir(dirp)) != NULL)
{
if (dir_entry->d_type != DT_DIR)
continue;
strcpy(dirname, "/proc/");
strcat(dirname, dir_entry->d_name);
handle_proc(dirname, filepath);
}
return 0;
}
int handle_proc(const char *dir, const char *filepath)
{
char dirname[MAXNAME];
char fdname[MAXNAME];
char filename[MAXNAME];
char buf[MAXNAME];
char str[MAXLINE];
char proc_name[MAXNAME];
char pid[MAXLINE];
struct dirent *dir_entry;
char *key;
char *value;
FILE *fp;
strcpy(dirname, dir);
strcat(dirname, "/fd");
DIR *dirp = opendir(dirname);
if (dirp == NULL)
return 0;
while ((dir_entry = readdir(dirp)) != NULL)
{
if (dir_entry->d_type != DT_LNK)
continue;
strcpy(fdname, dirname);
strcat(fdname, "/");
strcat(fdname, dir_entry->d_name);
int result = readlink(fdname, buf, MAXNAME - 1);
// 最后一个是我们要手动加的'\0'
// printf("%d-%d\n", result, strlen(buf));
// readlink 返回的后面没加'\0',不过返回了正确数,所以要手动加'\0'
if ((result < 0) || (result >= MAXNAME))
return -1;
buf[result] = '\0';
// printf("%s\n", buf);
if (strcmp(buf, filepath) == 0)
{
strcpy(filename, dirname);
strcat(filename, "/../status");
fp = fopen(filename, "r");
if (fp == NULL)
return 0; /* do nothing and normal return */
while ((fgets(str, MAXLINE, fp)) != NULL)
{
key = strtok(str, ":");
value = strtok(NULL, ":");
if (key != NULL && value != NULL)
{
while (*value == ' ' || *value == '\t')
value++;
// printf("----%s-----%s", key, value);
if (strcmp(key, "Name") == 0)
strcpy(proc_name, value);
if (strcmp(key, "Pid") == 0)
strcpy(pid, value);
}
}
fclose(fp);
pid[strlen(pid) - 1] = '\0';
proc_name[strlen(proc_name) - 1] = '\0';
printf("%s (pid:%s)\n", proc_name, pid);
break;
}
}
closedir(dirp);
return 0;
}