summary refs log tree commit diff
path: root/child.c
blob: 34b086ed5aeaa59aa711ae30df31fea775d967fa (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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <stdio.h>

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

struct ConnectionDataBuffer {
	size_t capacity;
	size_t length;
	char buf[];
};

struct ConnectionData {
	struct ConnectionDataBuffer *buffer;
};

static int
meowiero(struct FDWatchHandle *handle, enum FDWatch_EventType type, int fd, void *data)
{
	struct ConnectionData *connectiondata = (struct ConnectionData *)data;
	ssize_t readSize = 0;
	char c = 0;

	switch (type) {
	case FDWATCH_EVENT_INP:
		aura_printf("INPUT event in fd:%d\n", fd);

		readSize = read(fd, &connectiondata->buffer->buf[connectiondata->buffer->length],
				connectiondata->buffer->capacity - connectiondata->buffer->length);

		connectiondata->buffer->length = connectiondata->buffer->length + readSize;
		printf("%ld\n", readSize);
		if (errno != 0) {
			perror("read(2)");
			abort();
		}

		if (connectiondata->buffer->length == connectiondata->buffer->capacity) {
			aura_printf("Too much unread data!\n");
			abort();
		}

		aura_printf("%c\n", c);
		break;
	case FDWATCH_EVENT_HUP:
		aura_printf("HANGUP event in fd:%d, exiting\n", fd);
		fdwatcher_remove(handle, fd);
		close(fd);
		return 0;
	}

	return 1;
}

/* init */
int childProcessMain(int argc, char **argv)
{
	struct ConnectionData *connectiondata = { 0 };
	struct FDWatchHandle fdhandle = { 0 };
	int sockie = 0;
	int ret = 0;

	connectiondata = (struct ConnectionData *)malloc(sizeof(struct ConnectionData));
	if (errno != 0) {
		perror("malloc(3)");
		return 1;
	}

	connectiondata->buffer = malloc(sizeof(struct ConnectionDataBuffer) + 65536);
	if (errno != 0) {
		perror("malloc(3)");
		return 1;
	}
	connectiondata->buffer->capacity = 65536;

	/* socket fd int in argv[2]! ^w^ */
	sscanf(argv[2], "%d", &sockie);
	aura_printf("received fd:%d\n", sockie);

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

	ret = fdwatcher_add(&fdhandle, sockie, (void *)connectiondata);
	if (ret < 0) {
		aura_fprintf(stderr, "fdwatcher_add failed\n");
		return 1;
	}

	fdwatcher_watch(&fdhandle, meowiero);
	aura_printf("finished\n");

	return 0;
}