在 PHP 的 exec 中使用 mktime 运行 C 代码
我在使用 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
时间显然是错误的。任何人都知道可能导致此问题的原因是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在 C 代码上,而不是 PHP 代码上:
当您执行此操作时:
ptm
指针被mktime
函数修改。因此,如果你这样做:你实际上操纵指针两次,因此会出现奇怪的结果。
不用执行上述操作,只需执行以下操作:
您将得到预期的结果。因此,完整的
for
循环代码将是:The problem is with the C code, not the PHP code:
When you do this:
The
ptm
pointer is modified by themktime
function. Therefore, if you do this:You're actually manipulating the pointer twice, hence the weird results.
Instead of the above, just do:
You'll get the expected result. So, the complete
for
loop code would be: