-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
executable file
·89 lines (72 loc) · 2.16 KB
/
main.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
#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
#include <stdlib.h>
#include <string.h>
int find_pid_by_name( char* ProcName, int* foundpid)
{
DIR *dir;
struct dirent *d;
int pid, i;
char *s;
int pnlen;
i = 0;
foundpid[0] = 0;
pnlen = strlen(ProcName);
/* Open the /proc directory. */
dir = opendir("/proc");
if (!dir)
{
printf("cannot open /proc");
return -1;
}
/* Walk through the directory. */
while ((d = readdir(dir)) != NULL) {
char exe [PATH_MAX+1];
char path[PATH_MAX+1];
int len;
int namelen;
/* See if this is a process */
if ((pid = atoi(d->d_name)) == 0) continue;
snprintf(exe, sizeof(exe), "/proc/%s/exe", d->d_name);
if ((len = readlink(exe, path, PATH_MAX)) < 0)
continue;
path[len] = '\0';
/* Find ProcName */
s = strrchr(path, '/');
if(s == NULL) continue;
s++;
/* we don't need small name len */
namelen = strlen(s);
if(namelen < pnlen) continue;
if(!strncmp(ProcName, s, pnlen)) {
/* to avoid subname like search proc tao but proc taolinke matched */
if(s[pnlen] == ' ' || s[pnlen] == '\0') {
foundpid[i] = pid;
i++;
}
}
}
foundpid[i] = 0;
closedir(dir);
return 0;
}
int main()
{
char a[10];
int i, rv, pid_t[128];
/*if ( argc != 2 )
{
fprintf(stdout,"Usage %s procname\n",argv[0]);
return 0;
}
*/
printf("input :\n");
gets(a);
rv = find_pid_by_name( a, pid_t);
if(!rv) {
for(i=0; pid_t[i] != 0; i++)
printf("%d\n", pid_t[i]);
}
return 0;
}