summary refs log tree commit diff
path: root/parent.c
blob: a3cbb4a3d19ac4fe0cec9e4c056a6bc993d4837e (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
75
76
77
78
79
80
81
82
83
84
85
86
#include <sys/socket.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>

#include "fdwatcher.h"
#include "logging.h"
#include "network.h"

char *meowA = "haze";
char *meowB = "childprocess";

static int
handleNewConnection(int serverfd)
{
	char *childProcessArgv[4] = { meowA, meowB, "", NULL };
	struct sockaddr address = { 0 };
	socklen_t addrSize = sizeof(address);
	char chocolate[11] = { 0 };
	pid_t kwiat = 0;
	int sock = 0;

	sock = accept(serverfd, &address, &addrSize);
	if (errno != 0) {
		perror("accept(3)");
		return -1;
	}

	kwiat = fork();
	if (kwiat == 0) {
		snprintf((char *)&chocolate, 10, "%d", sock);
		childProcessArgv[2] = (char *)&chocolate;
		close(serverfd);
		execve("/proc/self/exe", childProcessArgv, NULL);
		perror("execve(3)");
		abort();
	}
	close(sock);

	return 0;
}

static int
meowie(struct FDWatchHandle *handle, enum FDWatch_EventType type, int fd, void *data)
{
	switch (type) {
	case FDWATCH_EVENT_INP:
		aura_printf("INPUT event in fd:%d\n", fd);
		handleNewConnection(fd);
		break;
	}

	return 1;
}

int
parentProcessMain(void)
{
	struct FDWatchHandle fdhandle = { 0 };
	int sock = 0;
	int ret = 0;

	sock = net_listen4(0, 4096, 0);
	if (sock < 0) {
		aura_fprintf(stderr, "net_listen4 failed\n");
		return 1;
	}

	ret = fdwatcher_initialise(&fdhandle, 1);
	if (ret < 0) {
		aura_fprintf(stderr, "fdwatcher_initialise failed\n");
		return 1;
	}

	ret = fdwatcher_add(&fdhandle, sock, NULL);
	if (ret < 0) {
		aura_fprintf(stderr, "fdwatcher_add failed\n");
		return 1;
	}

	aura_printf("Listening on fd:%d\n", sock);

	fdwatcher_watch(&fdhandle, meowie);
}