0

I have a program that has ill effects if run from .bashrc and I've dug deeper and found a minimal reproducible example.

The code below will print the elapsed time every second. If I run this program any time well after boot it outputs sequential seconds, as expected. If I run this program immediately after boot, manually or with .bashrc, the seconds in the output will skip at some point; from .bashrc at 24 they skip to 37 (then continue on as expected 38, 39...), if I run it manually from a shell it happens at some earlier time, depending on how long after boot I run it.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main (int argc, char *argv[]) { int start_time = time(NULL); int diff = 0; int prev = 0;

while (1)
{
    diff = difftime(time(NULL), start_time);
    if (diff != prev)
    {
        printf(&quot;Time: %d\n&quot;, diff);
    }
    prev = diff;
}

}

What could cause this?

user120300
  • 33
  • 6

2 Answers2

2

First of all: I also suggest together with all others from the comments, don't use ~/.bashrc to start a still running program. The best way is to create a service with a systemd Unit file.

The problem with your program is that the Raspberry Pi does not have a real time clock. It needs an internet connection and some time after boot up to initialize the network and to synchronize the local time with a time server on the internet. That is exactly the point where you see the "jump" in the time and continuing as expected. To solve your problem just take into account the time until synchronization with a time server has finished. Have a look at How to know if time is synced?.

Ingo
  • 42,961
  • 20
  • 87
  • 207
1

As an alternative to @Ingo's excellent answer; i.e. "do not try to start a progrm in ~/.bashrc - create a systemd Unit file instead.":

Do not try to start a progrm in ~/.bashrc - create a cron job instead.

Complete instructions for setting up a cron job to start your program each time the RPi boots may be found here.

Seamus
  • 23,558
  • 5
  • 42
  • 83