summaryrefslogtreecommitdiffstats
path: root/bidirtest.c
blob: 995b2226777b0e217c96884f3dceccdc03e7802b (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
70
71
72
73
74
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <wait.h>
#include <string.h>

volatile sig_atomic_t sig = 0;

char *cmd1[] = {"nc", "-l", "12345", NULL};
char *cmd2[] = {"nc", "-l", "12346", NULL};

void
handle_sig(int _sig, siginfo_t *siginfo, void *ucontext)
{
	sig = _sig;
}

int
main(int argc, char **argv)
{
	int p1[2], p2[2];
	pid_t pid1, pid2;

	struct sigaction act;
	memset(&act, 0, sizeof(act));

	act.sa_sigaction = &handle_sig;
	act.sa_flags = SA_SIGINFO;

	sigaction(SIGINT, &act, NULL);
	sigaction(SIGTERM, &act, NULL);
	sigaction(SIGHUP, &act, NULL);

	pipe(p1);
	pipe(p2);

	switch ((pid1 = fork())) {
	case 0:
		close(0);
		close(1);
		dup2(p1[0], 0);
		dup2(p2[1], 1);

		execvp(cmd1[0], cmd1);
		break;
	default:
		break;
	}

	switch ((pid2 = fork())) {
	case 0:
		close(0);
		close(1);
		dup2(p2[0], 0);
		dup2(p1[1], 1);

		execvp(cmd2[0], cmd2);
		break;
	default:
		break;
	}

	while (wait(NULL) != -1 || errno == EINTR) {
		if (sig != 0) {
			kill(pid1, sig);
			kill(pid2, sig);

			sig = 0;
		}
	}

	return 0;
}