Result of time() not updated after sleep() - c

I'm trying to pause my program for 1 second, and check the system time after that (I'm on Linux)
This is my testing program:
#include <stdio.h>
#include <unistd.h>
#include <time.h>
int main() {
time_t now = time(NULL);
struct tm *time_now = localtime(&now);
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);
int i = 0;
for (; i < 5; i++) {
sleep(1);
}
// This printf result is not as expected
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);
return 0;
}
The expected result is that the second printf would print +5 seconds. Instead, it prints the same time/seconds as the first printf.
I've found (maybe) the same problem posted here, but it doesn't seem to work:
sleep() and time() not functioning as expected inside for loop.
Sorry for my bad english, and thank you for your time.

Code is printing the original *time_now values - as expected.
Simply read time again to use new values.
time_t now = time(NULL);
struct tm *time_now = localtime(&now);
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);
int i = 0;
for (; i < 5; i++) {
sleep(1);
}
// Add
time_t now = time(NULL);
struct tm *time_now = localtime(&now);
printf("now: %d-%d\n", time_now->tm_min, time_now->tm_sec);

Related

How to trigger threads at specific system time under linux with C/C++?

As mentioned in title, how can I execute the specific threads at specific time accurately?
Is there any library help to do it?
For example, [00:00:00.00, 00:05:00.00, 00:10:00.00..04:00:00.00, 04:05:00.00...]
Here is my current approach to do it, is there any better way to do it?
#include <stdio.h>
#include <unistd.h>
#include <time.h>
unsigned interval = 5*60;
void until_next_tick(time_t *last_tick){
time_t now = time(NULL);
time_t next_tick = now / interval * interval + interval;
time_t diff = next_tick - now;
usleep(diff * 1000 * 1000);
*last_tick = next_tick;
}
void print_current_time(char *str){
time_t raw = time(NULL);
struct tm *curr = localtime(&raw);
sprintf(str, "%04d/%02d/%02d %02d:%02d:%02d",
curr->tm_year+1900, curr->tm_mon+1, curr->tm_mday,
curr->tm_hour, curr->tm_min, curr->tm_sec);
}
int main(int argc, char **argv)
{
time_t last_tick = time(NULL);
char str[30];
while (1) {
print_current_time(str);
printf("%s\n", str);
until_next_tick(&last_tick);
}
return 0;
}
Use timer_create with SIGEV_THREAD and set repeating time in timer_settime to start a new thread at a repeated time interval.
One simple way is to have a while(true) loop which calls sleep(1); and then in the loop checks what time it is with time(NULL) and if the time for a thread is past due, start the corresponding thread.
One simple way is using time() to get the time:
#include <stdio.h>
#include <time.h>
void *get_sys_stat(void* arg)
{
// Do somthing hrear
}
int main()
{
hour = 5;
min = 30;
int status = 0;
time_t t = time(NULL);
pthread_t sys_stat_thread;
while(1) {
/* Get time*/
struct tm tm = *localtime(&t);
/* Trigger another process or thread */
if ((tm.tm_hour == hour) && (tm.tm_min == min))
pthread_create(&sys_stat_thread, NULL, get_sys_stat, NULL);
}
}

Using difftime() in C

I am using difftime() to try to subtract two dates. But consider, as in this example, I'm getting incorrect result. Here's the code:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
const struct tm* stringToDate(const char *iDateStr)
{
struct tm *tm = (struct tm*)malloc(sizeof(struct tm));
memset(tm, 0, sizeof(struct tm));
sscanf_s(iDateStr, "%d-%d-%d", &tm->tm_mday, &tm->tm_mon, &tm->tm_year);
tm->tm_year -= 1900;
return tm;
}
const int stringDateDiffDays(const char *isDateTime1, const char *isDateTime2)
{
const struct tm *d1 = stringToDate(isDateTime1);
const struct tm *d2 = stringToDate(isDateTime2);
int diff = 0;
double diffSecs = 0;
// Seconds since start of epoch
diffSecs = difftime(mktime((struct tm*)d1), mktime((struct tm*)d2));
free((void *)d1);
free((void *)d2);
diff = (int)(diffSecs/(3600*24));
return diff;
}
int main(void)
{
char date1[] = "16-11-2017";
char date2[] = "16-12-2017";
printf("Date 1: %10s\n", date1);
printf("Date 2: %10s\n", date2);
printf("\nDifference : %d", stringDateDiffDays(date2, date1));
return 0;
}
What has happened? Is stringToDate() responsible for this, because of maybe the memset()? I am using Visual Studio 2012 to compile this code. How could I correctly implement these functions?

How can i get the current time in C with d/m/y format?

Which function can return current datetime with d/m/y format in C language?
EDIT:
here is my code:
#include <stdio.h>
#include <time.h>
int main()
{
time_t tmp_time;
struct tm * info;
time ( &tmp_time );
info = localtime ( &tmp_time );
printf ( "%s", asctime (info) );
}
this returns to me something like that Thu Jan 26 13:08:01 2017 and i would like to return 26/01/17 or 26/01/2017
Like this:
int main ()
{
time_t rawtime;
struct tm * currentTime;
time ( &rawtime );
currentTime = localtime ( &rawtime );
printf ( "%d/%d/%d", currentTime->tm_mday, currentTime->tm_mon+1, currentTime->tm_year+1900);
return 0;
}
Be careful, months are indexed since 0, and year is since 1900 in tm struct.
Perhaps like this:
#include <stdio.h>
#include <time.h>
int main()
{
time_t t = time(0);
if((time_t)-1 == t){
perror(0);
exit(1);
}
char buf[64];
struct tm tdata;
//I believe the 2 calls below should always succeed
//in this context
localtime_r(&t, &tdata);
strftime(buf, sizeof(buf), "%d/%m/%y", &tdata);
puts(buf);
}
The localtime(3) manpage says strftime is the recommended way to do it, and the strftime(3) manpage provides a similar example.
You can do it like this
#include <time.h>
#include <stdio.h>
int main(void)
{
time_t mytime = time(NULL);
struct tm date = *localtime(&mytime);
printf("now: %d/%d/%d\n", date.tm_mday,date.tm_mon + 1,date.tm_year +1900 );
return 0;
}
if you want to make it a function send the date as a parameter and return a int array holds day month and year

C Program to print Current Time

I am learning C program. When try to run the code I am getting error as : [Error] ld returned 1 exit status
#include <stdio.h>
#include <time.h>
void main()
{
time_t t;
time(&t);
clrscr();
printf("Today's date and time : %s",ctime(&t));
getch();
}
Can someone explain me What I am doing wrong here?
I tried this code :
int main()
{
printf("Today's date and time : %s \n", gettime());
return 0;
}
char ** gettime() {
char * result;
time_t current_time;
current_time = time(NULL);
result = ctime(&current_time);
return &result;
}
but still shows me error as : error: called object ‘1’ is not a function
in current_time = time(NULL); line. What is wrong with the code
I think your looking for something like this:
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
int main() {
time_t current_time;
char* c_time_string;
current_time = time(NULL);
/* Convert to local time format. */
c_time_string = ctime(&current_time);
printf("Current time is %s", c_time_string);
return 0;
}
you need to change clrscr(); to system(clear).Below is the working version of your code:
#include<stdio.h>
#include<time.h>
void main()
{
time_t t;
time(&t);
system("clear");
printf("Today's date and time : %s",ctime(&t));
}

Get current time in C, function

I want to get current time (without a current date) in C. The main problem is when I want to do it with functions. When I dont use them, evertyhing is just fine. Can anybody tell me, why my code shows only an hour? (take a look at the attached image). Thanks in advance.
#include <stdio.h>
#include <time.h>
#include <string.h>
char* get_time_string()
{
struct tm *tm;
time_t t;
char *str_time = (char *) malloc(100*sizeof(char));
t = time(NULL);
tm = localtime(&t);
strftime(str_time, sizeof(str_time), "%H:%M:%S", tm);
return str_time;
}
int main(int argc, char **argv)
{
char *t = get_time_string();
printf("%s\n", t);
return 0;
}
sizeof(str_time) gives you the size of char*. You want the size of the buffer str_time points to instead. Try
strftime(str_time, 100, "%H:%M:%S", tm);
// ^ size of buffer allocated for str_time
Other minor points - you should include <stdlib.h> to pick up a definition of malloc and should free(t) after printing its content in main.
The sizeof operator returns the length of the variable str_time which is a pointer to char. It doesn't returns the length of your dynamic array.
Replace sizeof(str_time) by 100 and it will go fine.
try this...
int main ()
{
time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
printf ( "Current local time and date: %s", asctime (timeinfo) );
return 0;
}
Use This Concept Getting System Time and Updating it. I have used this in my project many years before. you can change it as per your requirements.
updtime() /* FUNCTION FOR UPDATION OF TIME */
{
struct time tt;
char str[3];
gettime(&tt);
itoa(tt.ti_hour,str,10);
setfillstyle(1,7);
bar(getmaxx()-70,getmaxy()-18,getmaxx()-30,getmaxy()-10);
setcolor(0);
outtextxy(getmaxx()-70,getmaxy()-18,str);
outtextxy(getmaxx()-55,getmaxy()-18,":");
itoa(tt.ti_min,str,10);
outtextxy(getmaxx()-45,getmaxy()-18,str);
return(0);
}
The previous function will update time whenever you will call it like
and this will give you time
int temp;
struct time tt;
gettime(&tt); /*Get current time*/
temp = tt.ti_min;
If you want to update time the you can use the following code.
gettime(&tt);
if(tt.ti_min != temp) /*Check for any time update */
{
temp = tt.ti_min;
updtime();
}
This is complex code but if you understand it then it will solve your all problems.
Enjoy :)
In getting the time, you can try this one:
#include <stdio.h>
int main(void)
{
printf("Time: %s\n", __TIME__);
return 0;
}
Result:
Time: 10:49:49

Resources