[go: up one dir, main page]

File: dpopen.c

package info (click to toggle)
cctools 9.9-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 44,624 kB
  • sloc: ansic: 192,539; python: 20,827; cpp: 20,199; sh: 11,719; perl: 4,106; xml: 3,688; makefile: 1,224
file content (96 lines) | stat: -rw-r--r-- 1,668 bytes parent folder | download | duplicates (3)
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
93
94
95
96
#include "dpopen.h"

#include <unistd.h>
#include <sys/wait.h>

#include <errno.h>
#include <limits.h>
#include <signal.h>

extern char **environ;

pid_t dpopen(const char *command, FILE ** in, FILE ** out)
{
	pid_t pid;
	int i;
	int result;
	int stdin_fd[2];
	int stdout_fd[2];

	result = pipe(stdin_fd);
	if(result < 0)
		return 0;

	result = pipe(stdout_fd);
	if(result < 0) {
		close(stdin_fd[0]);
		close(stdin_fd[1]);
		return 0;
	}

	pid = fork();
	if(pid > 0) {
		close(stdin_fd[0]);
		close(stdout_fd[1]);

		*in = fdopen(stdin_fd[1], "w");
		if(*in == NULL) {
			close(stdin_fd[1]);
			close(stdout_fd[0]);
			kill(pid, SIGKILL);
			return 0;
		}
		*out = fdopen(stdout_fd[0], "r");
		if(*out == NULL) {
			fclose(*in);
			close(stdout_fd[0]);
			kill(pid, SIGKILL);
			return 0;
		}

		return pid;
	} else if(pid == 0) {
		close(stdin_fd[1]);
		close(stdout_fd[0]);

		close(STDIN_FILENO);
		dup2(stdin_fd[0], STDIN_FILENO);
		close(STDOUT_FILENO);
		dup2(stdout_fd[1], STDOUT_FILENO);
		close(STDERR_FILENO);
		dup2(stdout_fd[1], STDERR_FILENO);

		for(i = STDERR_FILENO + 1; i < _POSIX_OPEN_MAX; i++)
			close(i);

		return execl("/bin/sh", "sh", "-c", command, (char *) 0);
	} else {
		close(stdin_fd[0]);
		close(stdin_fd[1]);
		close(stdout_fd[0]);
		close(stdout_fd[1]);
		return 0;
	}
}

int dpclose(FILE * in, FILE * out, pid_t pid)
{
	if(in)
		fclose(in);
	if(out)
		fclose(out);

	while(1) {
		int status;
		int result = waitpid(pid, &status, 0);
		if(result == pid) {
			return WIFEXITED(status) ? status : -1;
		} else if(errno == EINTR) {
			continue;
		} else {
			return -1;	/* errno is set */
		}
	}
}

/* vim: set noexpandtab tabstop=4: */