Files
wmaker/src/osdep_linux.c
T

87 lines
1.7 KiB
C
Raw Normal View History

2010-03-19 14:09:48 +01:00
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <WINGs/WUtil.h>
2010-03-23 20:27:53 +01:00
#include "wconfig.h"
2013-05-15 13:07:57 +02:00
#include "osdep.h"
2010-03-19 14:09:48 +01:00
2010-03-26 20:25:27 +01:00
#define RETRY( x ) do { \
x; \
} while (errno == EINTR);
2010-03-19 14:09:48 +01:00
/*
* copy argc and argv for an existing process identified by `pid'
* into suitable storage given in ***argv and *argc.
*
2010-03-22 15:48:47 +01:00
* subsequent calls use the same static area for argv and argc.
*
* returns 0 for failure, in which case argc := 0 and argv := NULL
2010-03-19 14:09:48 +01:00
* returns 1 for success
*/
Bool GetCommandForPid(int pid, char ***argv, int *argc)
{
static char buf[_POSIX_ARG_MAX];
int fd, i, j;
ssize_t count;
*argv = NULL;
*argc = 0;
/* cmdline is a flattened series of null-terminated strings */
snprintf(buf, sizeof(buf), "/proc/%d/cmdline", pid);
2010-03-22 15:48:47 +01:00
while (1) {
2010-03-26 20:25:27 +01:00
/* not switching this to stdio yet, as this does not need
* to be portable, and i'm lazy */
2010-03-22 15:48:47 +01:00
if ((fd = open(buf, O_RDONLY)) != -1)
break;
if (errno == EINTR)
continue;
2010-03-19 14:09:48 +01:00
return False;
2010-03-22 15:48:47 +01:00
}
2010-03-19 14:09:48 +01:00
2010-03-22 15:48:47 +01:00
while (1) {
if ((count = read(fd, buf, sizeof(buf))) != -1)
break;
if (errno == EINTR)
continue;
2010-03-26 20:25:27 +01:00
RETRY( close(fd) )
2010-03-19 14:09:48 +01:00
return False;
}
2010-03-26 20:25:27 +01:00
RETRY( close(fd) )
2010-03-22 15:48:47 +01:00
/* count args */
2010-03-19 14:09:48 +01:00
for (i = 0; i < count; i++)
if (buf[i] == '\0')
(*argc)++;
if (*argc == 0)
return False;
2010-03-22 15:48:47 +01:00
*argv = (char **)wmalloc(sizeof(char *) * (*argc + 1 /* term. null ptr */));
2010-03-19 14:09:48 +01:00
(*argv)[0] = buf;
/* go through buf, set argv[$next] to the beginning of each string */
for (i = 0, j = 1; i < count; i++) {
if (buf[i] != '\0')
continue;
if (i < count - 1)
(*argv)[j++] = &buf[i + 1];
if (j == *argc)
break;
}
2010-03-22 15:48:47 +01:00
/* the list of arguments must be terminated by a null pointer */
(*argv)[j] = NULL;
2010-03-19 14:09:48 +01:00
return True;
}