Skip to content

Instantly share code, notes, and snippets.

@jackbergus
Created July 4, 2014 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackbergus/800ca4f4a17af69dc840 to your computer and use it in GitHub Desktop.
Save jackbergus/800ca4f4a17af69dc840 to your computer and use it in GitHub Desktop.
Run a R script inside a daemon
/*
* daemon.c
* This file is part of aviva2014
*
* Copyright (C) 2014 - Giacomo Bergami
*
* aviva2014 is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* aviva2014 is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with aviva2014. If not, see <http://www.gnu.org/licenses/>.
*/
extern "C" {
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
}
#define DAEMON_NAME "vdaemon"
#include <list>
#include <iostream>
#include <fstream>
#include <RInside.h>
void process(){
syslog (LOG_NOTICE, "Writing to my Syslog");
}
static inline std::string get_file_contents(const char *filename) {
std::ifstream in(filename, std::ios::in | std::ios::binary);
if (in)
{
std::string contents;
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
return(contents);
}
std::string s{};
return s;
}
int main(int argc, char *argv[]) {
//Set our Logging Mask and open the Log
setlogmask(LOG_UPTO(LOG_NOTICE));
openlog(DAEMON_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER);
syslog(LOG_INFO, "Entering Daemon");
pid_t pid, sid;
//Fork the Parent Process
pid = fork();
if (pid < 0) { exit(EXIT_FAILURE); }
//We got a good pid, Close the Parent Process
if (pid > 0) { exit(EXIT_SUCCESS); }
//Change File Mask
umask(0);
//Create a new Signature Id for our child
sid = setsid();
if (sid < 0) { exit(EXIT_FAILURE); }
//Close Standard File Descriptors
/* close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);*/
//----------------
//Main Process
//----------------
//Initializing R environment
RInside R(argc, argv);
//Running the script
std::string script = get_file_contents(argv[1]);
R.parseEvalQ(script.c_str());
//Close the log
closelog ();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment