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
85
86
87
88
89
90
91
92
|
/*
* Spawn services built on fork() for those libc's that lack spawning.
* $Id$
* Copyright (c) 1997 by Tycho Softworks.
* For conditions of distribution and reuse see product license.
*/
#include <proc/process.h>
#include <std/files.h>
static void spawn_redirect(int io, int mode)
{
int fd = open("/dev/null", mode);
if(fd < 0)
exit(EX_OSFILE);
if(fd != io)
{
dup2(fd, io);
close(fd);
}
}
static int spawn_wait(pid_t pid, int mode)
{
int waitflag = mode & P_WAIT;
/* -1 on fork failure */
if(pid == -1)
return -1;
if(!waitflag)
return pid;
waitpid(pid, &waitflag, 0);
return WEXITSTATUS(waitflag);
}
static void spawn_mode(int mode)
{
int i;
if(mode & P_BACKGROUND)
{
spawn_redirect(0, O_RDONLY);
spawn_redirect(1, O_WRONLY);
spawn_redirect(2, O_WRONLY);
}
for(i = 3; i < OPEN_MAX; ++i)
close(i);
if(mode & P_SESSION)
setsid();
}
int spawnv(const int mode, const char *path, char *const argv[])
{
pid_t pid = 0;
int status;
if(!(mode & P_OVERLAY))
pid = fork();
if(pid)
return spawn_wait(pid, mode);
spawn_mode(mode);
execv(path, argv);
exit(EX_UNAVAILABLE);
return -1;
}
int spawnvp(const int mode, const char *path, char *const argv[])
{
pid_t pid = 0;
int status;
if(!(mode & P_OVERLAY))
pid = fork();
if(pid)
return spawn_wait(pid, mode);
spawn_mode(mode);
execvp(path, argv);
exit(EX_UNAVAILABLE);
return -1;
}
|