-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathck.h
132 lines (119 loc) · 2.51 KB
/
ck.h
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
130
131
132
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <dirent.h>
#include <libgen.h>
/* checks if the string is purely an integer
* we can do it with `strtol' also
*/
int check_if_number (char *str)
{
int i;
for (i=0; str[i] != '\0'; i++)
{
if (!isdigit (str[i]))
{
return 0;
}
}
return 1;
}
#define MAX_BUF 1024
#define PID_LIST_BLOCK 32
int *pidof (char *pname)
{
DIR *dirp;
FILE *fp;
struct dirent *entry;
int *pidlist, pidlist_index = 0, pidlist_realloc_count = 1;
char path1[MAX_BUF], read_buf[MAX_BUF];
dirp = opendir ("/proc/");
if (dirp == NULL)
{
perror ("Fail");
return NULL;
}
pidlist = malloc (sizeof (int) * PID_LIST_BLOCK);
if (pidlist == NULL)
{
return NULL;
}
while ((entry = readdir (dirp)) != NULL)
{
if (check_if_number (entry->d_name))
{
strcpy (path1, "/proc/");
strcat (path1, entry->d_name);
strcat (path1, "/comm");
/* A file may not exist, it may have been removed.
* dut to termination of the process. Actually we need to
* make sure the error is actually file does not exist to
* be accurate.
*/
fp = fopen (path1, "r");
if (fp != NULL)
{
fscanf (fp, "%s", read_buf);
if (strcmp (read_buf, pname) == 0)
{
/* add to list and expand list if needed */
pidlist[pidlist_index++] = atoi (entry->d_name);
if (pidlist_index == PID_LIST_BLOCK * pidlist_realloc_count)
{
pidlist_realloc_count++;
pidlist = realloc (pidlist, sizeof (int) * PID_LIST_BLOCK * pidlist_realloc_count); //Error check todo
if (pidlist == NULL)
{
return NULL;
}
}
}
fclose (fp);
}
}
}
closedir (dirp);
pidlist[pidlist_index] = -1; /* indicates end of list */
return pidlist;
}
/*int function (char *path)
{
int *list, i;
if (argc != 2)
{
printf ("Usage: %s proc_name\n", path);
return 0;
}
list = pidof (path);
for (i=0; list[i] != -1; i++)
{
printf ("%d ", list[i]);
}
free (list);
if (list[0] != -1)
{
printf ("\n");
}
return 0;
}*/
/*int main (int argc, char *argv[])
{
int *list, i;
if (argc != 2)
{
printf ("Usage: %s proc_name\n", argv[0]);
return 0;
}
list = pidof (argv[1]);
for (i=0; list[i] != -1; i++)
{
printf ("%d ", list[i]);
}
free (list);
if (list[0] != -1)
{
printf ("\n");
}
return 0;
}*/