util.c (view raw)
1/*
2 * (C)opyright MMVI Anselm R. Garbe <garbeam at gmail dot com>
3 * See LICENSE file for license details.
4 */
5
6#include <stdarg.h>
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <sys/types.h>
11#include <sys/wait.h>
12#include <unistd.h>
13
14#include "util.h"
15
16static char *shell = NULL;
17
18void
19error(char *errstr, ...) {
20 va_list ap;
21 va_start(ap, errstr);
22 vfprintf(stderr, errstr, ap);
23 va_end(ap);
24 exit(1);
25}
26
27static void
28bad_malloc(unsigned int size)
29{
30 fprintf(stderr, "fatal: could not malloc() %d bytes\n",
31 (int) size);
32 exit(1);
33}
34
35void *
36emallocz(unsigned int size)
37{
38 void *res = calloc(1, size);
39 if(!res)
40 bad_malloc(size);
41 return res;
42}
43
44void *
45emalloc(unsigned int size)
46{
47 void *res = malloc(size);
48 if(!res)
49 bad_malloc(size);
50 return res;
51}
52
53void *
54erealloc(void *ptr, unsigned int size)
55{
56 void *res = realloc(ptr, size);
57 if(!res)
58 bad_malloc(size);
59 return res;
60}
61
62char *
63estrdup(const char *str)
64{
65 void *res = strdup(str);
66 if(!res)
67 bad_malloc(strlen(str));
68 return res;
69}
70
71void
72failed_assert(char *a, char *file, int line)
73{
74 fprintf(stderr, "Assertion \"%s\" failed at %s:%d\n", a, file, line);
75 abort();
76}
77
78void
79swap(void **p1, void **p2)
80{
81 void *tmp = *p1;
82 *p1 = *p2;
83 *p2 = tmp;
84}
85
86void
87spawn(Display *dpy, const char *cmd)
88{
89 if(!shell && !(shell = getenv("SHELL")))
90 shell = "/bin/sh";
91
92 if(!cmd)
93 return;
94 if(fork() == 0) {
95 if(fork() == 0) {
96 if(dpy)
97 close(ConnectionNumber(dpy));
98 setsid();
99 fprintf(stderr, "gridwm: execlp %s %s -c %s", shell, shell, cmd);
100 execlp(shell, shell, "-c", cmd, NULL);
101 fprintf(stderr, "gridwm: execlp %s", cmd);
102 perror(" failed");
103 }
104 exit (0);
105 }
106 wait(0);
107}
108
109void
110pipe_spawn(char *buf, unsigned int len, Display *dpy, const char *cmd)
111{
112 unsigned int l, n;
113 int pfd[2];
114
115 if(!shell && !(shell = getenv("SHELL")))
116 shell = "/bin/sh";
117
118 if(!cmd)
119 return;
120
121 if(pipe(pfd) == -1) {
122 perror("pipe");
123 exit(1);
124 }
125
126 if(fork() == 0) {
127 if(dpy)
128 close(ConnectionNumber(dpy));
129 setsid();
130 dup2(pfd[1], STDOUT_FILENO);
131 close(pfd[0]);
132 close(pfd[1]);
133 execlp(shell, shell, "-c", cmd, NULL);
134 fprintf(stderr, "gridwm: execlp %s", cmd);
135 perror(" failed");
136 }
137 else {
138 n = 0;
139 close(pfd[1]);
140 while(l > n) {
141 if((l = read(pfd[0], buf + n, len - n)) < 1)
142 break;
143 n += l;
144 }
145 close(pfd[0]);
146 buf[n - 1] = 0;
147 }
148 wait(0);
149}