Writing a CLI in C

Tags
Programming
Published
2018-02-04
Author
Man Parvesh Singh Randhawa
 
The first time I learned C was when I was in the first year of my undergrad studies at IIT Guwahati, India. After learning many other languages like C++ and Java, I wanted to try something out in C. So, I wrote a simple time reminder for my Ubuntu PC that notifies me of the time after every 30 minutes. Currently, this is a simple limit, but this can be changed easily.

Code breakdown

I will explain what all components do.
To notify on linux systems, we can use the notify-send command. We also define the following macros to reuse:
#define SNOTIFY "notify-send"#define ONE_SECOND_IN_MILLISECONDS 1000000
This function plays the notification sound:
void notification_sound(){ printf("\a\n");}
This function updates the time_t object passed to it and sets the value to current time:
void update_current_time(time_t mytime, struct tm ** timeinfo){ mytime = time(NULL); ctime(&mytime); *timeinfo = localtime (&mytime);}
These functions can be used to wait for a specified number of seconds:
void sleep_for_one_second(){ usleep(ONE_SECOND_IN_MILLISECONDS);}void sleep_for_n_seconds(int n){ int i; i = 0; while(i < n){ sleep_for_one_second(); i++; }}
And here is the main function that contains the core code:
int main(int argc, char const *argv[]){ int time_in_minutes; time_in_minutes = 30; int time_in_seconds;#ifdef DEBUG time_in_seconds = 1;#else time_in_seconds = time_in_minutes * 60;#endif time_t mytime; // waiting for time to reach :00 or :30 while(1) { struct tm * timeinfo; update_current_time(mytime, &timeinfo); sleep_for_one_second();#ifdef DEBUG printf("%d:%d:%d\n", timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec); // stops after 2 mins if (timeinfo->tm_min % 2 == 0) { break; }#else if (timeinfo->tm_min % 30 == 0) { break; }#endif // free(timeinfo); } // start alerting user after every 30 minutes from now while(1) { notification_sound(); char *system_call; struct tm * timeinfo; update_current_time(mytime, &timeinfo); sprintf(system_call, "%s \"It's %d:%d\"", SNOTIFY, timeinfo->tm_hour, timeinfo->tm_min); system(system_call); // wait for the specified time sleep_for_n_seconds(time_in_seconds); } return 0;}

Build and run

I created a simple MakeFile for the project with the following contents:
time_reminder: time_reminder.c gcc -o time_reminder time_reminder.c
After running make inside the folder where our C file is located, an executable time_reminder is generated. This executable can be run using:
./time_reminder