2 * vim:ts=4:sw=4:expandtab
10 #include <sys/types.h>
18 * This function tries to automatically find out where i3status is being piped
19 * to and choses the appropriate output format.
21 * It is a little hackish but should work for most setups :).
23 * By iterating through /proc/<number>/stat and finding out the parent process
24 * id (just like pstree(1) or ps(1) work), we can get all children of our
25 * parent. When the output of i3status is being piped somewhere, the shell
26 * (parent process) spawns i3status and the destination process, so we will
27 * find our own process and the pipe target.
29 * We then check whether the pipe target’s name is known and chose the format.
32 char *auto_detect_format() {
33 pid_t myppid = getppid();
34 pid_t mypid = getpid();
39 /* the relevant contents (for us) are:
40 * <pid> (<program name>) <status> <ppid>
41 * which should well fit into one page of 4096 bytes */
46 char *parentname = NULL;
48 if (!(dir = opendir("/proc")))
51 /* First pass: get the executable name of the parent.
52 * Upon error, we directly return NULL as we cannot continue without the
53 * name of our parent process. */
54 while ((entry = readdir(dir)) != NULL) {
55 pid_t pid = (pid_t)atoi(entry->d_name);
59 if (snprintf(path, sizeof(path), "/proc/%d/stat", pid) == -1 ||
60 !slurp(path, buffer, 4095))
64 char *leftbracket = strchr(buffer, '(');
65 char *rightbracket = strrchr(buffer, ')');
68 !(parentname = malloc((rightbracket - leftbracket))))
71 strcpy(parentname, leftbracket + 1);
79 while ((entry = readdir(dir)) != NULL) {
80 pid_t pid = (pid_t)atoi(entry->d_name);
81 if (pid == 0 || pid == mypid)
84 if (snprintf(path, sizeof(path), "/proc/%d/stat", pid) == -1)
90 /* Now we need to find out the name of the process.
91 * To avoid the possible race condition of the process existing already
92 * but not executing the destination (shell after fork() and before
93 * exec()), we check if the name equals its parent.
95 * We try this for up to 0.5 seconds, then we give up.
98 /* give the scheduler a chance between each iteration, don’t hog
103 if (!slurp(path, buffer, 4095))
106 char *leftbracket = strchr(buffer, '(');
107 char *rightbracket = strrchr(buffer, ')');
110 sscanf(rightbracket + 2, "%*c %d", &ppid) != 1 ||
113 *rightbracket = '\0';
114 name = leftbracket + 1;
115 } while (strcmp(parentname, name) == 0 && loopcnt++ < 10000);
120 /* Check for known destination programs and set format */
122 if (strcasecmp(name, "i3bar") == 0)
124 else if (strcasecmp(name, "dzen2") == 0)
126 else if (strcasecmp(name, "xmobar") == 0)
129 if (newfmt && format) {
130 fprintf(stderr, "i3status: cannot auto-configure, situation ambiguous (format \"%s\" *and* \"%s\" detected)\n", newfmt, format);