summaryrefslogtreecommitdiff
path: root/src/internal/slibtool_spawn_impl.h
blob: 93df1cddc1ace9299503a8208ea86d0653a0f7d8 (plain)
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/*******************************************************************/
/*  slibtool: a strong libtool implementation, written in C        */
/*  Copyright (C) 2016--2024  SysDeer Technologies, LLC            */
/*  Released under the Standard MIT License; see COPYING.SLIBTOOL. */
/*******************************************************************/

#ifndef SLIBTOOL_SPAWN_IMPL_H
#define SLIBTOOL_SPAWN_IMPL_H

#include <limits.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdbool.h>
#include <errno.h>
#include <sys/wait.h>

#ifndef PATH_MAX
#define PATH_MAX (_XOPEN_PATH_MAX < 4096) ? 4096 : _XOPEN_PATH_MAX
#endif

#ifndef SLBT_USE_FORK
#ifndef SLBT_USE_VFORK
#ifndef SLBT_USE_POSIX_SPAWN
#define SLBT_USE_POSIX_SPAWN
#endif
#endif
#endif

#ifdef  SLBT_USE_POSIX_SPAWN
#include <spawn.h>
#endif

static inline int slbt_spawn(
	struct slbt_exec_ctx *	ectx,
	bool			fwait)
{
	pid_t	pid;

#ifdef SLBT_USE_POSIX_SPAWN

	if (posix_spawnp(
			&pid,
			ectx->program,
			0,0,
			ectx->argv,
			ectx->envp))
		pid = -1;

#else

#ifdef SLBT_USE_FORK
	pid = fork();
#else
	pid = vfork();
#endif

#endif

	if (pid < 0) {
		ectx->pid      = pid;
		ectx->exitcode = errno;
		return -1;
	}

	if (pid == 0) {
		execvp(
			ectx->program,
			ectx->argv);
		_exit(errno);
	}

	errno     = 0;
	ectx->pid = pid;

	if (fwait)
		return waitpid(
			pid,
			&ectx->exitcode,
			0);

	return 0;
}

#endif