]> git.sur5r.net Git - i3/i3status/blob - src/process_runs.c
Support for (Debian) GNU/kFreeBSD
[i3/i3status] / src / process_runs.c
1 // vim:ts=8:expandtab
2 #include <stdbool.h>
3 #include <glob.h>
4 #include <string.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <unistd.h>
9 #include <stdio.h>
10 #include <stdlib.h>
11
12 #ifndef LINUX
13 /* TODO: correctly check for *BSD */
14 #include <sys/param.h>
15 #include <sys/sysctl.h>
16 #include <sys/resource.h>
17 #endif
18
19 #include "i3status.h"
20
21 /*
22  * Checks if the PID in path is still valid by checking:
23  *  (Linux) if /proc/<pid> exists
24  *  (NetBSD) if sysctl returns process infos for this pid
25  *
26  */
27 bool process_runs(const char *path) {
28         char pidbuf[16];
29         static glob_t globbuf;
30         int fd;
31         memset(pidbuf, 0, sizeof(pidbuf));
32
33         if (glob(path, GLOB_NOCHECK | GLOB_TILDE, NULL, &globbuf) < 0)
34                 die("glob() failed\n");
35         fd = open((globbuf.gl_pathc > 0 ? globbuf.gl_pathv[0] : path), O_RDONLY);
36         globfree(&globbuf);
37         if (fd < 0)
38                 return false;
39         (void)read(fd, pidbuf, sizeof(pidbuf));
40         (void)close(fd);
41
42 #if defined(LINUX) || defined(__GNU__) || defined(__GLIBC__)
43         struct stat statbuf;
44         char procbuf[512];
45         (void)snprintf(procbuf, sizeof(procbuf), "/proc/%ld", strtol(pidbuf, NULL, 10));
46         return (stat(procbuf, &statbuf) >= 0);
47 #else
48         /* TODO: correctly check for NetBSD. Evaluate if this runs on OpenBSD/FreeBSD */
49         struct kinfo_proc info;
50         size_t length = sizeof(struct kinfo_proc);
51         int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, strtol(pidbuf, NULL, 10) };
52         if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
53                 return false;
54         return (length != 0);
55 #endif
56 }