feat: Initial Commit
This commit is contained in:
commit
b67b62a31a
|
@ -0,0 +1,2 @@
|
|||
build/
|
||||
.cache/
|
|
@ -0,0 +1,5 @@
|
|||
cmake_minimum_required(VERSION 3.15)
|
||||
project(HostController)
|
||||
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
|
||||
set(CMAKE_BUILD_TYPE Debug)
|
||||
add_executable(HostController main.c)
|
|
@ -0,0 +1,59 @@
|
|||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <spawn.h>
|
||||
#include <unistd.h>
|
||||
#include <string.h>
|
||||
#include <errno.h>
|
||||
|
||||
bool ports[999];
|
||||
|
||||
void start_worker(int port) {
|
||||
char portStr[6];
|
||||
sprintf(portStr, "%d", port);
|
||||
char *argv[] = {"./worker", portStr, NULL};
|
||||
extern char **environ;
|
||||
|
||||
pid_t pid;
|
||||
posix_spawn(&pid, "./worker", NULL, NULL, argv, environ);
|
||||
}
|
||||
|
||||
int main() {
|
||||
struct sockaddr_in server_addr;
|
||||
server_addr.sin_family = AF_INET;
|
||||
server_addr.sin_port = htons(1337);
|
||||
server_addr.sin_addr.s_addr = INADDR_ANY;
|
||||
|
||||
printf("Starting Server\n");
|
||||
int socket_fd;
|
||||
socket_fd = socket(AF_INET, SOCK_STREAM, 0);
|
||||
int bound = bind(socket_fd, (struct sockaddr*)&server_addr, sizeof(server_addr));
|
||||
if(bound < 0) {
|
||||
printf("Bind Error: %s (%d)\n", strerror(errno), errno);
|
||||
return 1;
|
||||
}
|
||||
listen(socket_fd, 5);
|
||||
|
||||
while(true) {
|
||||
struct sockaddr_in client_addr;
|
||||
int client_size = sizeof(client_addr);
|
||||
int client_sock = accept(socket_fd, (struct sockaddr*)&client_addr, &client_size);
|
||||
|
||||
for(int i = 0; i < sizeof(ports); i++) {
|
||||
if(!ports[i]) {
|
||||
int port = 11000+i;
|
||||
printf("Assigning port %i to worker\n", port);
|
||||
char buff[4];
|
||||
memcpy(buff, &port, sizeof(int));
|
||||
write(client_sock, buff, sizeof(buff));
|
||||
start_worker(port);
|
||||
ports[i] = true;
|
||||
shutdown(client_sock, SHUT_RDWR);
|
||||
close(client_sock);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
Loading…
Reference in New Issue