new unix socket stuff

I can't get logfiles to work though
This commit is contained in:
2025-07-19 23:47:34 +02:00
parent e0274fb6d5
commit c776501adc

View File

@ -2,13 +2,20 @@
#include <stdio.h> #include <stdio.h>
#include <sys/types.h> #include <sys/types.h>
#include <unistd.h> #include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
pid_t pid;
int server_sock;
struct sockaddr_un server;
int sockaddr_len;
int main() { int main() {
/* /*
Setup daemon Setup daemon
Used this for basic idea => https://en.wikipedia.org/wiki/Daemon_(computing) Used this for basic idea => https://en.wikipedia.org/wiki/Daemon_(computing)
*/ */
pid_t pid;
pid_t sid; pid_t sid;
pid = fork(); pid = fork();
@ -33,12 +40,68 @@ int main() {
close(STDOUT_FILENO); close(STDOUT_FILENO);
close(STDERR_FILENO); close(STDERR_FILENO);
/* TODO: Setup HTTP server */ FILE *stdout;
/* TODO: API needed */ FILE *stderr;
/* TODO: switch to mode 'a' later */
stdout = fopen("/tmp/out_log.txt", "w");
stderr = fopen("/tmp/err_log.txt", "w");
if (out_log == NULL || err_log == NULL) {
return 1;
}
/* Setup Unix Socket */
server_sock = socket(AF_UNIX, SOCK_STREAM, 0);
if (sock == -1) {
return 1;
}
server.sun_family = AF_UNIX;
strcpy(server.sun_path, "/tmp/test_sock");
unlink(server.sun_path);
sockaddr_len = strlen(server.sun_path) + sizeof(server.sun_family);
if (bind(server_sock, (struct sockaddr*)&server, sockaddr_len) == -1) {
return 1;
}
if (listen(server_sock, 3) == -1) {
return 1;
}
printf("Listening on %s\n", server.sun_path);
/* Actual program */ /* Actual program */
char should_close = 0; int client_sock;
while(!should_close) { char receive_buf[1000];
sleep(1); char send_buf[1000];
memset(receive_buf, 0, sizeof receive_buf);
memset(send_buf, 0, sizeof send_buf);
while(1) {
client_sock = accept(sock, NULL, NULL);
if (sock2 == -1) {
return 1;
} }
data_length = recv(sock2, receive_buf, sizeof receive_buf, 0);
if (data_length <= 0) {
strcpy(send_buf, "Failed to receive any data.");
send(client_sock, send_buf, strops_length(send_buf), 0);
close(client_sock);
continue;
}
if (strops_contains(send_buf, "shutdown now!")) {
strcpy(send_buf, "Shutting down.");
send(client_sock, send_buf, strops_length(send_buf), 0);
close(client_sock);
break;
}
close(client_sock);
}
close(server_sock);
return 0;
} }