xref: /haiku/src/system/libroot/posix/unistd/system.cpp (revision cbe0a0c436162d78cc3f92a305b64918c839d079)
1 /*
2  * Copyright 2004-2011, Ingo Weinhold, ingo_weinhold@gmx.de.
3  * Distributed under the terms of the MIT License.
4  */
5 
6 #include <image.h>
7 
8 #include <errno.h>
9 #include <pthread.h>
10 #include <stdlib.h>
11 #include <sys/wait.h>
12 #include <unistd.h>
13 
14 #include <errno_private.h>
15 #include <syscall_utils.h>
16 
17 
18 extern "C" int
19 system(const char *command)
20 {
21 	if (!command)
22 		return 1;
23 
24 	const char *argv[] = { "/bin/sh", "-c", command, NULL };
25 	int argc = 3;
26 
27 	thread_id thread = load_image(argc, argv, (const char **)environ);
28 	if (thread < 0)
29 		RETURN_AND_SET_ERRNO_TEST_CANCEL(thread);
30 
31 	resume_thread(thread);
32 
33 	int exitStatus;
34 	pid_t result;
35 	while ((result = waitpid(thread, &exitStatus, 0)) < 0
36 		&& errno == B_INTERRUPTED) {
37 		// waitpid() was interrupted by a signal, retry...
38 	}
39 
40 	if (result < 0)
41 		return -1;
42 
43 	return exitStatus;
44 }
45