1

I have very simple code that should run on background and at 1 am shut down the computer:

#include <ctime>
#include <cstdlib>
#include <unistd.h>

int main() {
    time_t t;struct tm * now;
    daemon(0,0);
    while(1){
        t = time(0);
        now = localtime( & t );
        if(now->tm_hour==1){
           system("shutdown -P");
           break;
        }
        sleep(10);
    }
    return 0;
} 

The code works without sleep(10) but uses whole free memory so I need sleep function there to stop loop and recheck time each ten seconds, but with sleep function program stops immediately after I run it.

Dipto
  • 2,720
  • 2
  • 22
  • 42
Ruli
  • 2,592
  • 12
  • 30
  • 40
  • 1
    How do you know it stops ? You call daemon() so it'll put itself in the background, and not consume any noticeable resources/CPU. – nos Jan 03 '14 at 14:05
  • Check the return value of daemon() – Chinna Jan 03 '14 at 14:06
  • As a side note, did you know that `shutdown` already has the feature you are implementing? (`shutdown -P 01:00`) – rodrigo Jan 03 '14 at 14:14

2 Answers2

1

If you are writing C code, don't use C++ headers (ctime, cstdlib). Replace those #includes with #include <stdlib.h> and #include <time.h>. If the behavior of this code is really as you describe (which I would find surprising), then this is probably the source of the error.

Andrey Mishchenko
  • 3,986
  • 2
  • 19
  • 37
1

Of course it immediately exits. Thats the whole point of using daemon. Check with ps and you will see that your proram is still running as a seperate process now.

Check the man page for a desription how daemon works.

Devolus
  • 21,661
  • 13
  • 66
  • 113