• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #include <fcntl.h>
2 #include <unistd.h>
3 #include <errno.h>
4 #include <string.h>
5 #include <spawn.h>
6 #include <unsupported_api.h>
7 #include "stdio_impl.h"
8 #include "syscall.h"
9 
10 extern char **__environ;
11 
popen(const char * cmd,const char * mode)12 FILE *popen(const char *cmd, const char *mode)
13 {
14 	int p[2], op, e;
15 	pid_t pid;
16 	FILE *f;
17 	posix_spawn_file_actions_t fa;
18 
19 	UNSUPPORTED_API_VOID(LITEOS_A);
20 	if (*mode == 'r') {
21 		op = 0;
22 	} else if (*mode == 'w') {
23 		op = 1;
24 	} else {
25 		errno = EINVAL;
26 		return 0;
27 	}
28 
29 	if (pipe2(p, O_CLOEXEC)) return NULL;
30 	f = fdopen(p[op], mode);
31 	if (!f) {
32 		__syscall(SYS_close, p[0]);
33 		__syscall(SYS_close, p[1]);
34 		return NULL;
35 	}
36 
37 	e = ENOMEM;
38 	if (!posix_spawn_file_actions_init(&fa)) {
39 		for (FILE *l = *__ofl_lock(); l; l=l->next)
40 			if (l->pipe_pid && posix_spawn_file_actions_addclose(&fa, l->fd))
41 				goto fail;
42 		if (!posix_spawn_file_actions_adddup2(&fa, p[1-op], 1-op)) {
43 			if (!(e = posix_spawn(&pid, "/bin/sh", &fa, 0,
44 			    (char *[]){ "sh", "-c", (char *)cmd, 0 }, __environ))) {
45 				posix_spawn_file_actions_destroy(&fa);
46 				f->pipe_pid = pid;
47 				if (!strchr(mode, 'e'))
48 					fcntl(p[op], F_SETFD, 0);
49 				__syscall(SYS_close, p[1-op]);
50 				__ofl_unlock();
51 				return f;
52 			}
53 		}
54 fail:
55 		__ofl_unlock();
56 		posix_spawn_file_actions_destroy(&fa);
57 	}
58 	fclose(f);
59 	__syscall(SYS_close, p[1-op]);
60 
61 	errno = e;
62 	return 0;
63 }
64