summaryrefslogtreecommitdiff
path: root/lib/libc/stdio/popen.c
blob: a1ef6a9f506cf8aa992e8c3eb7ef1908eb590116 (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
#include <__stdio.h>
#include <stddef.h> // for NULL

#include <errno.h>  // for EINVAL, errno
#include <fcntl.h>  // for O_RDONLY, O_CLOEXEC, O_WRONLY
#include <stdio.h>  // for FILE, fclose, fdopen, popen
#include <unistd.h> // for close, dup2, _exit, execl, fork, pipe2, STDIN_F...

FILE *popen(const char *command, const char *mode)
{
	struct __FILE *stream;
	int oflag;
	int pipefd[2];

	switch (*mode) {
	case 'r':
		oflag = O_RDONLY;
		break;
	case 'w':
		oflag = O_WRONLY;
		break;
	default:
		errno = EINVAL;
		return NULL;
	}

	if (pipe2(pipefd, O_CLOEXEC) < 0)
		return NULL;

	stream = fdopen(pipefd[oflag], mode);
	if (stream == NULL) {
		close(pipefd[0]);
		close(pipefd[1]);
		return NULL;
	}

	pid_t pid = fork();

	if (pid < 0) {
		close(pipefd[0]);
		close(pipefd[1]);
		fclose(stream);
		return NULL;
	}

	if (pid == 0) {
		if (oflag == O_RDONLY) {
			dup2(pipefd[1], STDOUT_FILENO);
			close(pipefd[0]);
			close(pipefd[1]);
		} else {
			dup2(pipefd[0], STDIN_FILENO);
			close(pipefd[0]);
			close(pipefd[1]);
		}
		execl("/bin/sh", "sh", "-c", command, (char *)0);
		_exit(127);
	} else {
		if (oflag == O_RDONLY) {
			close(pipefd[1]);
		} else {
			close(pipefd[0]);
		}

		stream->pid = pid;

		return stream;
	}
}