【问题标题】:Running C code with mktime inside PHP's exec在 PHP exec 中使用 mktime 运行 C 代码
【发布时间】:2011-11-17 20:34:14
【问题描述】:

我在使用 PHP 和使用当前时间的 C 脚本时遇到了一个奇怪的问题。我的程序有点复杂,但问题仅限于此:

我有这个 C 代码,它打印 1 分钟前的日期、当前日期和 1 分钟后的日期:

#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;
}

当我在 shell 中运行它时,我得到了正确的结果(打印格式是月份的日期、小时、分钟):

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

但是,当我通过 PHP 执行它时,我得到了奇怪的结果。这是PHP代码:

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

这是输出:

17 20 7
17 17 8
17 14 9

时间显然是错误的。任何人都知道可能导致这种情况的原因吗?

【问题讨论】:

  • var_dump($output) 得到什么?
  • @jprofitt array(3) { [0]=&gt; string(8) "17 17 40" [1]=&gt; string(8) "17 14 41" [2]=&gt; string(8) "17 11 42" }
  • 您想使用 C 来获取日期信息的任何特殊原因? PHP 的内置日期函数有什么问题?
  • @NullUserExceptionఠ_ఠ 我的 C 程序更大,并使用时间/日期来计算我想要的。我只是想在页面中显示结果,但结果是错误的,因为 C 代码中的时间是错误的(尽管当我使用 shell 时它们似乎是正确的)。

标签: php c date mktime


【解决方案1】:

问题在于 C 代码,而不是 PHP 代码:

当你这样做时:

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++;

【讨论】:

  • 谢谢。这解决了它。我不知道mktime 修改了指针。但是为什么它在 shell 中工作而不是在 PHP 中呢?
  • @nmat:说真的?不知道。一开始它根本不应该起作用。您的示例中可能缺少一些我需要回答的内容。
  • 并非如此。实际上,我在此处发布之前将其复制并粘贴到不同的文件中以确保发生了什么。我看到here mktime 的返回值是“自 Epoch 编码为 time_t 类型的值以来的指定时间”(如果我没有跳到“返回值”部分,我也会读到它修改了指针)。无论如何,我写的确实是多余的,但我认为不应该给出错误的结果......
  • 我想我必须检查汇编程序才能弄清楚。
  • 别打扰了。感谢您的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-09
  • 2015-05-24
  • 2023-04-03
  • 2020-03-21
  • 2015-04-03
  • 2015-01-12
相关资源
最近更新 更多