Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a proper way to write a program that runs continuously

Tags:

c

linux

shell

cron

I want to continuously execute a C program on my computer. It doesn't actually have to "do" anything until it identifies an event though.

For example, the C program could be written with a do while loop that never exits. Inside the loop, there could be an if else condition that listens for an event. Lets say "if a file exists in a directory, then open the file and do something, else take a break and sleep(60) for a minute".

Of course this functionality can be implemented outside the C program. I could run the same idea above in the shell script..."if a file exists in a directory, then run C program, else take a break and sleep(60) for a minute". I could also write a shell script to execute the C program if a file exists and run the shell program with a crontab or some other scheduler.

If I didn't run sleep or I set the crontab to a very high frequency, then obviously my response time would improve. While that would be ideal, I have my doubts that is a safe and proper way to do this. I basically want my program to always be ready for action...an event occurs, get to work!

Since I've never implemented such a program, my question is, is there a proper and safe way of creating an "event-listener" that serves this type of functionality? C vs shell approach? Other ideas?

like image 832
ThatsRightJack Avatar asked Nov 08 '22 10:11

ThatsRightJack


1 Answers

What you are actually want is to communicate between process. using 'sleep()' and check a condition can be done but this is not the optimal way in terms of CPU consumption.

There for there several ways to communicate between processes, I know these:

  1. pipe
  2. shared memory
  3. socket
  4. Fifo

it is good to start pipe: this can be use when you have 2 programs and you want program #1 to wait to some event from program #2. I found an example here but there are many others in google.

after that I would continue with socket. one example is here but again, there are many more in the web.

for further reading I can advice you to look for the book "Advanced Linux Programming" in chapter "Interprocess Communication".

like image 60
stzahi Avatar answered Nov 15 '22 06:11

stzahi