aboutsummaryrefslogtreecommitdiffstats
path: root/src/process.c
blob: e2fb6b3cfba863caf8f425d70556e29988eed9db (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include "process.h"
#include "err.h"
#include "log.h"
#include <errno.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

int
spawn(char **argv)
{
	pid_t pid;
	int status;

	if (!argv[0] || *argv[0] == '\0') {
		return SF_ERR_INVALID_ARG;
	}

	if ((pid = fork()) < 0) {
		log_write(LOG_ERR, "fork error: %s", strerror(errno));
		return -errno;
	}

	if (pid == 0) {
		execvp(argv[0], argv);

		_exit(errno == ENONET ? 127 : 126);
	}

	if (waitpid(pid, &status, 0) < 0) {
		return -errno;
	}

	if (WIFEXITED(status)) {
		int exit_code = WEXITSTATUS(status);
		if (exit_code != 0) {
			log_write(LOG_ERR, "Command failed with code %d",
				  exit_code);
			return SF_ERR_EXEC_FAILED;
		}
	} else if (WIFSIGNALED(status)) {
		return SF_ERR_SIGNALED;
	}

	return SF_OK;
}