#include "fork_program.h"
#include "kext_tools_util.h"
#include <spawn.h>
#include <sys/wait.h>
#include <libc.h>
#include <crt_externs.h>
int fork_program(const char * argv0, char * const argv[], Boolean wait)
{
int result;
int spawn_result;
pid_t child_pid;
int child_status;
int normal_iopolicy = getiopolicy_np(IOPOL_TYPE_DISK,
IOPOL_SCOPE_PROCESS);
char ** environ = *(_NSGetEnviron());
if (!wait) {
setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, IOPOL_THROTTLE);
}
spawn_result = posix_spawn(&child_pid, argv0, NULL,
NULL, argv, environ);
if (spawn_result != 0) {
OSKextLog( NULL, kOSKextLogErrorLevel,
"posix_spawn failed for %s.", argv0);
errno = spawn_result;
result = -2;
goto finish;
}
OSKextLog( NULL, kOSKextLogDetailLevel,
"started child process %s[%d] (%ssynchronous).",
argv0, child_pid, wait ? "" : "a");
if (wait) {
OSKextLogSpec logSpec = kOSKextLogDetailLevel;
if (waitpid(child_pid, &child_status, 0) == -1) {
result = -1;
goto finish;
}
if (WIFEXITED(child_status)) {
result = WEXITSTATUS(child_status);
if (result) {
logSpec = kOSKextLogErrorLevel;
}
OSKextLog( NULL, logSpec,
"Child process %s[%d] exited with status %d.",
argv0, child_pid, result);
} else if (WIFSIGNALED(child_status)) {
result = WTERMSIG(child_status);
logSpec = kOSKextLogErrorLevel;
OSKextLog( NULL, logSpec,
"Child process %s[%d] exited due to signal %d.",
argv0, child_pid, result);
} else {
result = -1;
}
} else {
result = child_pid;
}
finish:
setiopolicy_np(IOPOL_TYPE_DISK, IOPOL_SCOPE_PROCESS, normal_iopolicy);
return result;
}