all repos — dwm @ 366d81e313e6dd4e9e6c61ed8dfca4b4b40ccde6

fork of suckless dynamic window manager

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			setsid();
 97			if(dpy)
 98				close(ConnectionNumber(dpy));
 99			execlp(shell, "shell", "-c", cmd, NULL);
100			fprintf(stderr, "gridwm: execvp %s", cmd);
101			perror(" failed");
102		}
103		exit (0);
104	}
105	wait(0);
106}
107
108void
109pipe_spawn(char *buf, unsigned int len, Display *dpy, const char *cmd)
110{
111	unsigned int l, n;
112	int pfd[2];
113
114	if(!shell && !(shell = getenv("SHELL")))
115		shell = "/bin/sh";
116
117	if(!cmd)
118		return;
119
120	if(pipe(pfd) == -1) {
121		perror("pipe");
122		exit(1);
123	}
124
125	if(fork() == 0) {
126		setsid();
127		if(dpy)
128			close(ConnectionNumber(dpy));
129		dup2(pfd[1], STDOUT_FILENO);
130		close(pfd[0]);
131		close(pfd[1]);
132		execlp(shell, "shell", "-c", cmd, NULL);
133		fprintf(stderr, "gridwm: execvp %s", cmd);
134		perror(" failed");
135	}
136	else {
137		n = 0;
138		close(pfd[1]);
139		while(l > n) {
140			if((l = read(pfd[0], buf + n, len - n)) < 1)
141				break;
142			n += l;
143		}
144		close(pfd[0]);
145		buf[n - 1] = 0;
146	}
147	wait(0);
148}