daemonize

This commit is contained in:
MAO Dongyang 2023-03-29 17:13:13 +02:00
parent 962ee7180e
commit 0f0c9a48dc
No known key found for this signature in database
7 changed files with 126 additions and 14 deletions

View File

@ -0,0 +1,12 @@
CC=gcc
all: main clean
main: main.o
$(CC) -o main main.o
main.o: main.c
$(CC) -c main.c
clean:
rm -f *.o

View File

@ -0,0 +1 @@
coucou, je suis bien en vie!

75
System2/daemonize/main.c Normal file
View File

@ -0,0 +1,75 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <stdbool.h>
bool daemonize()
{
pid_t pid = fork();
if (pid < 0)
{
return false;
}
if (pid > 0)
{
exit(0);
}
if (setsid() < 0)
{
return false;
}
pid = fork();
if (pid < 0)
{
return false;
}
if (pid > 0)
{
exit(0);
}
umask(0);
chdir("/");
FILE *fp;
fp = fopen("/Users/mdy/Development/langage_C/System2/daemonize/test.txt", "w");
close(STDIN_FILENO);
close(STDOUT_FILENO);
dup(fileno(fp));
close(STDERR_FILENO);
dup(fileno(fp));
return true;
}
void handler(int signum)
{
if (signum == SIGUSR1)
{
FILE *fp;
fp = fopen("/Users/mdy/Development/langage_C/System2/daemonize/coucou.txt", "w");
fprintf(fp, "coucou, je suis bien en vie!\n");
fclose(fp);
}
else if (signum == SIGUSR2)
{
exit(EXIT_SUCCESS);
}
else
{
printf("received signal %d\n", signum);
}
}
int main(void)
{
daemonize();
if (signal(SIGUSR1, handler) == SIG_ERR)
printf("can't catch SIGUSR1\n");
if (signal(SIGUSR2, handler) == SIG_ERR)
printf("can't catch SIGUSR2\n");
for (;;)
pause();
}

View File

View File

@ -0,0 +1,12 @@
CC=gcc
all: main clean
main: main.o
$(CC) -o main main.o
main.o: main.c
$(CC) -c main.c
clean:
rm -f *.o

View File

@ -1,23 +1,34 @@
#include <stdio.h> #include <stdio.h>
#include <signal.h> #include <signal.h>
#include <unistd.h> #include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
void handler(int signum) void handler(int signum)
{ {
FILE *fp; if (signum == SIGUSR1)
fp = fopen("test.txt", "w");
fprintf(fp, "coucou, je suis bien en vie!\n");
fclose(fp);
}
int main()
{
signal(SIGUSR1, handler);
for (size_t i = 0; i < 30; i++)
{ {
FILE *fp;
printf("i = %d, In main\n", i); fp = fopen("test.txt", "w");
sleep(1); fprintf(fp, "coucou, je suis bien en vie!\n");
fclose(fp);
}
else if (signum == SIGUSR2)
{
exit(EXIT_SUCCESS);
}
else
{
printf("received signal %d\n", signum);
} }
return 0;
} }
int main(void)
{
if (signal(SIGUSR1, handler) == SIG_ERR)
printf("can't catch SIGUSR1\n");
if (signal(SIGUSR2, handler) == SIG_ERR)
printf("can't catch SIGUSR2\n");
for (;;)
pause();
}

View File

@ -0,0 +1 @@
coucou, je suis bien en vie!