Search code examples
c++clinuxinfinite-loopdaemon

Does endless While loop take up CPU resources?


From what I understand, you write your Linux Daemon that listens to a request in an endless loop.
Something like..

int main() {
    while(1) {
        //do something...
    }
}

ref: http://www.thegeekstuff.com/2012/02/c-daemon-process/

I read that sleeping a program makes it go into waiting mode so it doesn't eat up resources.

1.If I want my daemon to check for a request every 1 second, would the following be resource consuming?

int main() {
    while(1) {
        if (request) {
            //do something...
        }
        sleep(1)
    }
}

2.If I were to remove the sleep, does it mean the CPU consumption will go up 100%?

3.Is it possible to run an endless loop without eating resources? Say..if it does nothing but just loops itself. Or just sleep(1).

Endless loops and CPU resources is a mystery to me.


Solution

  • Is it possible to run an endless loop without eating resources? Say..if it does nothing but just loops itself. Or just sleep(1).

    There ia a better option.
    You can just use a semaphore, which remains blocked at the begining of loop and you can signal the semaphore whenever you want the loop to execute.
    Note that this will not eat any resources.