go-daemon/c-daemon/daemon/daemon.c

73 lines
1.4 KiB
C
Raw Normal View History

2023-07-26 13:52:50 +03:00
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/fs.h>
#include <linux/limits.h>
#define NR_OPEN 1024
2023-07-26 15:29:40 +03:00
void logg(int num){
printf("You are in: %d\n",num);
}
2023-07-26 13:52:50 +03:00
int _daemon(int nochdir, int noclose){
pid_t pid, sid;
// pid_t defined in sys/types.h
// pid_t is a signed int data type
2023-07-26 15:29:40 +03:00
2023-07-27 12:55:19 +03:00
logg(1);
2023-07-26 13:52:50 +03:00
pid = fork(); // fork of the parent process
// fork() function defined in unistd.h
2023-07-26 15:29:40 +03:00
2023-07-27 12:55:19 +03:00
logg(2);
2023-07-26 13:52:50 +03:00
if (pid < 0){
2023-07-27 12:55:19 +03:00
logg(3);
2023-07-26 13:52:50 +03:00
exit(EXIT_FAILURE); // exit and EXIT_FAILURE defined in stdlib.h
}
else if (pid > 0){
2023-07-27 12:55:19 +03:00
logg(4);
2023-07-26 13:52:50 +03:00
exit(EXIT_SUCCESS);
}
2023-07-26 15:29:40 +03:00
2023-07-27 12:55:19 +03:00
logg(5);
2023-07-26 15:29:40 +03:00
sid = setsid();
2023-07-27 12:55:19 +03:00
logg(6);
2023-07-26 15:29:40 +03:00
if (sid < 0) {
2023-07-27 12:55:19 +03:00
logg(7);
2023-07-26 15:29:40 +03:00
exit(EXIT_FAILURE);
}
2023-07-27 12:55:19 +03:00
logg(8);
2023-07-26 15:29:40 +03:00
if ((chdir("/")) < 0) {
2023-07-27 12:55:19 +03:00
logg(10);
2023-07-26 15:29:40 +03:00
exit(EXIT_FAILURE);
}
2023-07-27 12:55:19 +03:00
logg(11);
2023-07-26 15:45:46 +03:00
if (!noclose) {
2023-07-27 12:55:19 +03:00
logg(12);
2023-07-26 15:58:21 +03:00
for (int i = 0; i < NR_OPEN; i++){
2023-07-27 12:55:19 +03:00
logg(13);
2023-07-26 15:45:46 +03:00
close(i);
2023-07-26 15:58:21 +03:00
// close(STDOUT_FILENO); => close(1);
// close(STDERR_FILENO); => close(2);
}
2023-07-26 15:45:46 +03:00
open("/dev/null", O_RDWR);
2023-07-27 12:55:19 +03:00
logg(14);
2023-07-26 15:45:46 +03:00
dup(0);
dup(0);
}
2023-07-26 13:52:50 +03:00
while (1) {
2023-07-27 12:55:19 +03:00
logg(15);
2023-07-27 12:22:51 +03:00
int status = system("/usr/lib/cdaemontmp/info");
2023-07-26 13:52:50 +03:00
// TODO SECURITY ISSUE
// LINK https://stackoverflow.com/questions/5237482/how-do-i-execute-an-external-program-within-c-code-in-linux-with-arguments#
sleep(1);
}
2023-07-27 12:55:19 +03:00
logg(16);
2023-07-26 13:52:50 +03:00
exit(EXIT_SUCCESS);
}