Skip to content

Instantly share code, notes, and snippets.

@takamin
Last active August 29, 2015 14:22
Show Gist options
  • Save takamin/7cc9a245536510c630e3 to your computer and use it in GitHub Desktop.
Save takamin/7cc9a245536510c630e3 to your computer and use it in GitHub Desktop.
C言語でラズパイのデーモンを作るときの補助関数とスケルトン
#include <stdio.h>
#include <unistd.h>
#include <stdarg.h>
#include <signal.h>
#include <syslog.h>
static int daemonized = 0; /* daemonized flag */
int daemonize(
const char* pidfilepath,
const char *syslog_ident,
int syslog_option,
int syslog_facility)
{
daemonized = 0; /* initialize */
if (daemon(0, 0) != -1) {
/* success to daemonize. */
daemonized = 1;
/* open syslog */
if(syslog_ident) {
openlog(syslog_ident, syslog_option, syslog_facility);
}
/* write daemon pid to the file */
if(pidfilepath) {
FILE* pidfile = fopen(pidfilepath, "w+");
if (pidfile) {
int pid = getpid();
fprintf(pidfile, "%d\n", pid);
fclose(pidfile);
} else {
syslog(LOG_ERR,
"daemonize() : failed to write pid.\n");
}
}
}
return daemonized;
}
#ifdef __cplusplus__
extern "C" {
#endif
/*!
* create a typical daemon process.
*
* @param [in] pidfilepath The pid file pathname.
* If NULL, it will never record.
* @param [in] syslog_ident syslog ident.
* @param [in] syslog_option syslog option.
* @param [in] syslog_facility syslog facility.
* @return this function 1:a daemon created, 0: error
*/
int daemonize(
const char* pidfilepath,
const char *syslog_ident,
int syslog_option,
int syslog_facility);
#ifdef __cplusplus__
}
#endif
#include <stdio.h>
#include <unistd.h>
#include <syslog.h>
#include "daemonize.h"
/* The following codes are only sample */
static volatile int sigterm = 0;
static void handle_sigterm(int sig) { sigterm = 1; }
static int mydaemon( void )
{
syslog(LOG_INFO, "mydaemon started.\n");
signal(SIGTERM, handle_sigterm);
while(!sigterm) {
/*
* Here's cyclic daemon codes.
*/
usleep(1000000);
}
syslog(LOG_INFO, "mydaemon stopped.\n");
return 0;
}
int main(int argc, char* argv[])
{
if(!daemonize("/var/run/mydaemon.pid",
"daemon", LOG_PID, LOG_DAEMON))
{
fprintf(stderr, "failed to daemonize.\n");
return 2; /* fail to start daemon */
}
return mydaemon();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment