Skip to content

Instantly share code, notes, and snippets.

@anilmuppalla
Created December 14, 2012 20:06
Show Gist options
  • Select an option

  • Save anilmuppalla/4288221 to your computer and use it in GitHub Desktop.

Select an option

Save anilmuppalla/4288221 to your computer and use it in GitHub Desktop.
#include <stdlib.h>
#include <unistd.h>
#include <syslog.h>
int main(int argc, char *argv[]) {
pid_t pid, sid;
/* Clone ourselves to make a child */
pid = fork();
/* If the pid is less than zero,
* something went wrong when forking */
if (pid < 0) {
exit(EXIT_FAILURE);
}
/* If the pid we got back was greater
* than zero, then the clone was
* successful and we are the parent. */
if (pid > 0) {
exit(EXIT_SUCCESS);
}
/* If execution reaches this point we are the child */
/* Set the umask to zero */
umask(0);
/* Open a connection to the syslog server */
openlog(argv[0],LOG_NOWAIT|LOG_PID,LOG_USER);
/* Sends a message to the syslog daemon */
syslog(LOG_NOTICE, "Successfully started daemon\n");
char *cwd = getcwd(NULL, 0);
syslog(LOG_NOTICE, "CWD: %s", cwd);
free(cwd);
/* Change the current working directory */
if ((chdir("/")) < 0) {
syslog(LOG_ERR, "Could not change working directory to /\n");
exit(EXIT_FAILURE);
}
char *ccwd = getcwd(NULL, 0);
syslog(LOG_NOTICE, "CWD: %s", ccwd);
free(ccwd);
/* Close the standard file descriptors */
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
/* A useless payload to demonstrate */
syslog(LOG_INFO, "Daemon will exit now....\n");
/* this is optional and only needs to be done when your daemon exits */
closelog();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment