Fix Debian builds
[wmaker-crm.git] / src / osdep_linux.c
blobfd97f59b3342c6895dad0dec322a9ae5f534fcba
2 #include <sys/types.h>
3 #include <sys/stat.h>
5 #include <errno.h>
6 #include <fcntl.h>
7 #include <limits.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <unistd.h>
12 #include <WINGs/WUtil.h>
14 #include "wconfig.h"
16 #define RETRY( x ) do { \
17 x; \
18 } while (errno == EINTR);
21 * copy argc and argv for an existing process identified by `pid'
22 * into suitable storage given in ***argv and *argc.
24 * subsequent calls use the same static area for argv and argc.
26 * returns 0 for failure, in which case argc := 0 and argv := NULL
27 * returns 1 for success
29 Bool GetCommandForPid(int pid, char ***argv, int *argc)
31 static char buf[_POSIX_ARG_MAX];
32 int fd, i, j;
33 ssize_t count;
35 *argv = NULL;
36 *argc = 0;
38 /* cmdline is a flattened series of null-terminated strings */
39 snprintf(buf, sizeof(buf), "/proc/%d/cmdline", pid);
40 while (1) {
41 /* not switching this to stdio yet, as this does not need
42 * to be portable, and i'm lazy */
43 if ((fd = open(buf, O_RDONLY)) != -1)
44 break;
45 if (errno == EINTR)
46 continue;
47 return False;
50 while (1) {
51 if ((count = read(fd, buf, sizeof(buf))) != -1)
52 break;
53 if (errno == EINTR)
54 continue;
55 RETRY( close(fd) )
56 return False;
58 RETRY( close(fd) )
60 /* count args */
61 for (i = 0; i < count; i++)
62 if (buf[i] == '\0')
63 (*argc)++;
65 if (*argc == 0)
66 return False;
68 *argv = (char **)wmalloc(sizeof(char *) * (*argc + 1 /* term. null ptr */));
69 (*argv)[0] = buf;
71 /* go through buf, set argv[$next] to the beginning of each string */
72 for (i = 0, j = 1; i < count; i++) {
73 if (buf[i] != '\0')
74 continue;
75 if (i < count - 1)
76 (*argv)[j++] = &buf[i + 1];
77 if (j == *argc)
78 break;
81 /* the list of arguments must be terminated by a null pointer */
82 (*argv)[j] = NULL;
83 return True;