Running C code with mktime inside PHP exec

I am having a strange problem with a PHP and C script that uses the current time. My program is a bit complicated, but the problem boils down to this:

I have this C code that prints the date 1 minute ago, the current date and the date after 1 minute:

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

int main(int argc, char **argv){
  char date[9];
  time_t rawtime;
  struct tm * ptm;
  int i;

  time(&rawtime);
  ptm = gmtime(&rawtime);
  ptm->tm_min--;

  for(i = 0; i < 3; i++){
    rawtime = mktime(ptm);
    ptm = gmtime(&rawtime);
    snprintf(date, 9, "%d %d %d", ptm->tm_mday, ptm->tm_hour, ptm->tm_min);
    printf("%s\n", date);

    ptm->tm_min++;
  }
  return 0;
}

When I run this in the shell, I get the correct results (print format - day of the month, hour, minute):

$ ./test
17 20 7
17 20 8
17 20 9

However, when I execute it through PHP, I get strange results. This is the PHP code:

<?php
exec("path_to_exec/test", $output);
echo "$output[0]<br/>";
echo "$output[1]<br/>";
echo "$output[2]<br/>";
?>

And this is the result:

17 20 7
17 17 8
17 14 9

The clock is clearly wrong. Does anyone have any idea what could be causing this?

+5
source share
1 answer

The problem is with the C code, not the PHP code:

When you do this:

rawtime = mktime(ptm);

ptm mktime. , :

rawtime = mktime(ptm);
ptm = gmtime(&rawtime);

, , .

:

mktime(ptm);
snprintf(...);

. , for :

mktime(ptm);
snprintf(date, 9, "%d %d %d", ptm->tm_mday, ptm->tm_hour, ptm->tm_min);
printf("%s\n", date);
ptm->tm_min++;
+3

All Articles