문제

I am having a strange problem with PHP and a C script that uses the current time. My program is a little complex, but the problem narrows itself to this:

I have this C code which prints the date 1 minute ago, the current date, and the date 1 minute from now:

#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 correct results (the print format is 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 output:

17 20 7
17 17 8
17 14 9

The hours are clearly wrong. Anyone has any idea of what could be causing this?

도움이 되었습니까?

해결책

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

When you do this:

rawtime = mktime(ptm);

The ptm pointer is modified by the mktime function. Therefore, if you do this:

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

You're actually manipulating the pointer twice, hence the weird results.

Instead of the above, just do:

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

You'll get the expected result. So, the complete for loop code would be:

mktime(ptm);
snprintf(date, 9, "%d %d %d", ptm->tm_mday, ptm->tm_hour, ptm->tm_min);
printf("%s\n", date);
ptm->tm_min++;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top