summaryrefslogtreecommitdiff
path: root/IPC.cpp
blob: 215a15c9081c0570750b292b61e1d603ce0b0579 (plain) (blame)
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
#include "IPC.h"

#include <cstring>
#include <sys/socket.h>
#include <iostream>
#include <unistd.h>

using std::cout, std::endl;

static const char* path = "/tmp/YATwm.sock";

IPCModule::IPCModule(CommandsModule& commandsModule, Config& cfg, Globals& globals)
	:commandsModule(commandsModule),
	 cfg(cfg),
	 globals(globals)
{
	sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
	address.sun_family = AF_UNIX;
	strcpy(address.sun_path, path);
	unlink(address.sun_path);
	len = strlen(address.sun_path) + sizeof(address.sun_family);

	if(bind(sockfd, (sockaddr*)&address, len) == -1)
	{
		cout << "ERROR" << endl;
	}
	cout << "SOCKETED" << endl;
}

void IPCModule::doListen()
{
	if(listen(sockfd, 1) != 0)
	{
		cout << "ERROR 2" << endl;
		return;
	}
	if(first)
	{
		first = false;
		return;
	}
	cout << "DOLISTEN" << endl;
	unsigned int socklen = 0;
	sockaddr_un remote;
	int newsock = accept(sockfd, (sockaddr*)&remote, &socklen);
	cout << "LISTENING" << endl;
	char buffer[256];
	memset(buffer, 0, 256);
	read(newsock, buffer, 256);
	std::string command(buffer);
	while(command[command.size() - 1] == 0 || command[command.size() - 1] == '\n')
		command = command.substr(0, command.size() - 1);
	//cout << '"' << command << '"' << endl;
	try
	{
		commandsModule.runCommand(command);
	}
	catch(Err e)
	{
		cout << e.code << " " << e.message << endl;
	}
	char* message = "RAN COMMAND";
	send(newsock, message, strlen(message), 0);
	cout << "RAN COMMAND" << endl;
	shutdown(newsock, SHUT_RDWR);
	close(newsock);
}

void IPCModule::quitIPC()
{
	close(sockfd);
	cout << path << endl;
}

int IPCModule::getFD()
{
	if(sockfd > 0)
		return sockfd;
	return -1;
}