[helpers] Added an ability to become a daemon;

master
leonid-ed 8 years ago
parent 6c9d847cb7
commit 3c0d3570f8

@ -37,6 +37,7 @@
#include <stdint.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
int openlistener_socket(int port)
{
@ -115,3 +116,55 @@ int normalize_path(char *path)
return 0;
}
#define DM_MAX_CLOSE 8192
int daemonize(void)
{
pid_t pid;
/* fork */
pid = fork();
if (pid == -1) {
perror("fork() failed");
return EFAULT;
}
else if (pid != 0) {
exit(EXIT_SUCCESS);
}
/* create new session and progress group */
if (setsid() == -1) {
perror("setsid() failed");
return EFAULT;
}
/* set the working directory to the root directory */
if (chdir("/") == -1) {
perror("chdir() failed");
return EFAULT;
}
/* close all open files */
int fd;
int maxfd = sysconf(_SC_OPEN_MAX);
if (maxfd == -1)
maxfd = DM_MAX_CLOSE; /* if this limit is indeterminate, take a guess */
for (fd = 0; fd < maxfd; fd++)
close(fd);
/* reopen standard fd's /dev/null */
close(STDIN_FILENO);
fd = open("/dev/null", O_RDWR);
if (fd != STDIN_FILENO) { /* fd should be 0 */
return EBADFD;
}
if (dup2(STDIN_FILENO, STDOUT_FILENO) != STDOUT_FILENO) {
return EBADFD;
}
if (dup2(STDIN_FILENO, STDERR_FILENO) != STDERR_FILENO) {
return EBADFD;
}
return 0;
}

@ -36,4 +36,6 @@ static inline void version_print(FILE *fso)
}
#endif
int daemonize(void);
#endif /* __SXMP_EXAMPLES_HELPERS_H__ */

Loading…
Cancel
Save