aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/src/process.c
blob: 9d9503780aba4949f763922c7025c3c70240c6cd (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 "log.h"

#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

static int wait_for_child(pid_t pid, int *ec)
{
	int status;

	pid_t ret = waitpid(pid, &status, 0);
	if (ret < 0) {
		print_errno("waitpid");
		return ret;
	}

	if (WIFEXITED(status))
		*ec = WEXITSTATUS(status);
	else
		*ec = -1;

	return 0;
}

int proc_spawn(const char *args[], int *ec)
{
	int ret = 0;

	pid_t child_pid = fork();
	if (child_pid < 0) {
		print_errno("fork");
		return child_pid;
	}

	if (child_pid)
		return wait_for_child(child_pid, ec);

	ret = execv(args[0], (char *const *)args);
	if (ret < 0) {
		print_errno("execv");
		exit(ret);
	}

	return 0;
}