Skip to content

Instantly share code, notes, and snippets.

@elrok123
Created April 24, 2015 22:33
Show Gist options
  • Save elrok123/4b2cd3c92f69fbe68225 to your computer and use it in GitHub Desktop.
Save elrok123/4b2cd3c92f69fbe68225 to your computer and use it in GitHub Desktop.
Simple time daemon to periodically save the time to a file every 5 seconds using UNIX libraries and C
//Include required libraries
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <syslog.h>
int main(int argc, char ** argv)
{
//Create variable for storing time
time_t rawtime;
//Create file pointer
FILE * fp;
//Create a new process
pid_t process_id;
//Fork this program creating a new child from this program and store the returned value in process_id
process_id = fork();
//Check to see if the process ID was set and created properly by checking if process_id is not equal to 0
if(process_id != 0)
exit(0);
//Run this loop infinitely
while(1)
{
//Create a new file or overwrite the one that exists at "/tmp/localtime-5secs", and store the pointer to the file in fp
fp = fopen("/tmp/localtime-5secs", "w");
//Get the time and set rawtime to the value
time(&rawtime);
//Write the time to the file
fprintf(fp, ctime(&rawtime));
//Close the file pointer
fclose(fp);
//Flush the file output buffer for any rogue characters
fflush(fp);
//Pause for 5 seconds on each execution of the loop
sleep(5);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment