Skip to content

Instantly share code, notes, and snippets.

@alirezaarzehgar
Created November 6, 2022 07:22
Show Gist options
  • Select an option

  • Save alirezaarzehgar/5fc3c5386205e93ae9e116d79ea241cf to your computer and use it in GitHub Desktop.

Select an option

Save alirezaarzehgar/5fc3c5386205e93ae9e116d79ea241cf to your computer and use it in GitHub Desktop.
A deamon for sending poem form poem.conf to clients based on KISS <3
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <syslog.h>
#include <setjmp.h>
#include <time.h>
#include <errno.h>
#include <err.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#ifndef DEBUG
#define perror(msg) syslog(LOG_ERR, "%s: %s", msg, strerror(errno))
#define err(status, msg) perror(msg), _exit(status)
#endif
sigjmp_buf jmp;
void
sighub (__attribute__ ((unused)) int signo)
{
siglongjmp (jmp, 1);
}
int
main()
{
int sfd, cfd;
char poem[BUFSIZ];
struct sockaddr_in sa;
FILE *fpoem = NULL;
#ifndef DEBUG
if (daemon (0, 0))
err (1, "daemon");
#endif
if (signal (SIGHUP, sighub))
err (1, "signal");
if ((sfd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1)
err (1, "socket");
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = htonl (INADDR_ANY);
sa.sin_port = htons (1073);
if (bind (sfd, (struct sockaddr *)&sa, sizeof (sa)))
err (1, "bind");
if (listen (sfd, 10))
err (1, "listen");
if (sigsetjmp (jmp, 1))
fclose (fpoem), close (cfd);
if (! (fpoem = fopen ("/etc/poem.conf", "r")))
err (1, "/etc/poem.conf");
for (;;) {
if ((cfd = accept (sfd, NULL, NULL)) == -1)
perror ("accept");
srand (time (NULL) + rand());
fseek (fpoem, 0, SEEK_END);
fseek (fpoem, rand() % ftell (fpoem), SEEK_SET);
while (ftell (fpoem) > 0
&& fgetc (fpoem) != '\n')
fseek (fpoem, -2, SEEK_CUR);
fgets (poem, BUFSIZ, fpoem);
write (cfd, poem, strlen (poem));
close (cfd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment