Showing posts with label patch. Show all posts
Showing posts with label patch. Show all posts

Monday, May 05, 2008

perl 调用 localtime 的时区问题

测试用例:
{
local $ENV{TZ} = 'UTC+0';
print scalar localtime, "\n";
}
print scalar localtime, "\n";

@CentOS 4.2
Mon Sep 24 01:05:52 2007
Mon Sep 24 01:05:52 2007

@CentOS 4.4
Mon Sep 24 01:05:52 2007
Mon Sep 24 09:05:52 2007

Bug 的详情可以参考
http://rt.perl.org/rt3/Public/Bug/Display.html?id=26136
摘要:
* threaded perl calls localtime_r(3) instead of localtime(3)
* localtime(3) calls tzset(3), but localtime_r(3) does not

一些时间类的模块受此影响,比如 Date::Simple。

CentOS 4.4/ Red Hat Enterprise Linux 4 Update 4 已解决此问题,详情见 perl 的 changelog:
$ rpm -q --changelog perl
* Thu May 11 2006 Jason Vas Dias <jvdias@redhat.com> - 3:5.8.5-30.RHEL4

- fix errata testing issues:
o bug 161305 localtime_r_needs_tzset incorrectly not set on 64-bit arches
o generate perl headers correctly to avoid missing / unresolved headers

* Thu Apr 06 2006 Jason Vas Dias <jvdias@redhat.com> - 3:5.8.5-28.RHEL4

- fix bug 161305: call tzset() before localtime_r

而 perl 的 community patch 应用于 perl 5.8.8 发布之后,此后发布的新版本目前只有 perl 5.10.0。

综上,有以下数种对应解决办法:
1、如果 OS 为 CentOS 4.4 以下,使用 yum 直接升级 perl 即可。
2、其他 OS 可以查找是否有相应的 vendor patch。
3、自行编译安装禁用线程(-Uusethreads)的 perl。
4、自行编译安装 perl 5.10.0。
5、给受影响的模块打补丁,Date::Simple 的补丁这里有。

相关链接:
小心时区陷阱(一)
小心时区陷阱(二)

Sunday, December 10, 2006

小心时区陷阱(二)

测试用例
#!/usr/bin/perl
use strict;
use warnings;
use Time::Piece qw//;
use Date::Simple qw//;
use POSIX qw//;

sub show_info {
my $msg = shift;
my $hour = (localtime)[2];
printf "tz=$ENV{TZ}, tzname=%s:%s, hour=%2d # $msg\n", POSIX::tzname, $hour;
}

$ENV{TZ} = 'JST-9';
print "Date::Simple version is $Date::Simple::VERSION\n";
show_info('start');
my $date = Date::Simple->new;
show_info('after new');
$date->strftime("%Y-%m-%d\n");
show_info('after strftime');
POSIX::tzset;
show_info('after tzset');


输出结果
tz=JST-9, tzname=JST:JST, hour= 8 # start
tz=JST-9, tzname=JST:JST, hour= 8 # after new
tz=JST-9, tzname=UTC:UTC, hour=23 # after strftime
tz=JST-9, tzname=JST:JST, hour= 8 # after tzset


另外,关于 $ENV{TZ},提醒一下。
假设机器的时区设置为 UTC+9,不考虑非法的时区设置,那么根据值的不同,分别会是这样的结果
1.  not exists $ENV{TZ}        UTC+9
2.1 if ( $ENV{TZ} ) {...} UTC+0
2.2 else {...} UTC+9


Patch for Date::Simple 3.02
$ diff -r Date-Simple-3.02.orig Date-Simple-3.02
diff -r Date-Simple-3.02.orig/lib/Date/Simple.pm Date-Simple-3.02/lib/Date/Simple.pm
158a159
>
160,161c161,174
< local $ENV{TZ} = 'UTC+0';
< return POSIX::strftime ($format, _gmtime ($self));
---
> my $exists_env_tz = exists $ENV{TZ};
> my $tz = $ENV{TZ} if $exists_env_tz;
>
> $ENV{TZ} = 'UTC+0';
> my $result = POSIX::strftime ($format, _gmtime ($self));
>
> if ( $exists_env_tz ) {
> $ENV{TZ} = $tz;
> } else {
> delete $ENV{TZ};
> }
> POSIX::tzset();
>
> return $result;

参考链接
rt#23875