#include #include #include #include #include #include #include #include #include #include #include "getoutput_demo/getoutput.h" char debug_mode = 0; int child(){ int logfile_fd; if(!debug_mode){ close(0); close(1); close(2); logfile_fd = open("daemon_log", O_WRONLY | O_CREAT | O_TRUNC, 0644); dup2(logfile_fd, 1); dup2(logfile_fd, 2); } chdir("/"); // Wikipedia points out a lot of daemons do this struct sockaddr_in sad; sad.sin_port = htons(5130); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; int skt = socket(AF_INET, SOCK_STREAM, 0); // Step 1 if(skt == -1){ perror("socket"); return 1; } if( bind(skt, (struct sockaddr*)(&sad), sizeof(struct sockaddr_in)) ){ // step 2 perror("bind"); return 1; } if( listen(skt, 5) ){ // step 3 perror("listen"); return 1; } while(1){ int client_fd; struct sockaddr_in client_address; socklen_t address_size = sizeof(struct sockaddr_in); client_fd = accept(skt, (struct sockaddr *)(&client_address), &address_size); // step 4 char *usernames = getoutput("who | cut -d ' ' -f 1 | sort -u"); dprintf(1, "Client connected from IP %s\n", inet_ntoa(client_address.sin_addr)); write(client_fd, usernames, strlen(usernames)); free(usernames); close(client_fd); } // Won't run anyway close(logfile_fd); return 0; } int main(int argc, char ** argv){ if(argc > 1 && !strcmp(argv[1], "--debug")) debug_mode = 1; if(debug_mode) child(); else { pid_t pid = fork(); if(pid) { // parent process return 0; } else { // child process child(); } } }