73 lines
No EOL
1.4 KiB
C
73 lines
No EOL
1.4 KiB
C
#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
|
|
|
|
void logg(int num){
|
|
printf("You are in: %d\n",num);
|
|
}
|
|
|
|
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
|
|
|
|
logg(1);
|
|
pid = fork(); // fork of the parent process
|
|
// fork() function defined in unistd.h
|
|
|
|
logg(2);
|
|
if (pid < 0){
|
|
logg(3);
|
|
exit(EXIT_FAILURE); // exit and EXIT_FAILURE defined in stdlib.h
|
|
}
|
|
else if (pid > 0){
|
|
logg(4);
|
|
exit(EXIT_SUCCESS);
|
|
}
|
|
|
|
logg(5);
|
|
sid = setsid();
|
|
|
|
logg(6);
|
|
if (sid < 0) {
|
|
logg(7);
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
logg(8);
|
|
if ((chdir("/")) < 0) {
|
|
logg(10);
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
logg(11);
|
|
if (!noclose) {
|
|
logg(12);
|
|
for (int i = 0; i < NR_OPEN; i++){
|
|
logg(13);
|
|
close(i);
|
|
// close(STDOUT_FILENO); => close(1);
|
|
// close(STDERR_FILENO); => close(2);
|
|
}
|
|
open("/dev/null", O_RDWR);
|
|
logg(14);
|
|
dup(0);
|
|
dup(0);
|
|
}
|
|
while (1) {
|
|
logg(15);
|
|
int status = system("/usr/lib/cdaemontmp/info");
|
|
// 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);
|
|
}
|
|
logg(16);
|
|
exit(EXIT_SUCCESS);
|
|
} |