我正在使用File :: Temp创建临时文件.程序正常退出时,我的临时文件会自动删除.我期望当我的程序用ctrl c停止时会发生同样的情况.它不是.
这是一个简单的程序,展示了我的问题.
期望的行为是这样的.我怎样才能实现它?我在Linux上.
>关闭文件句柄时不删除临时文件(ok)
>当程序正常退出时,临时文件被删除(ok)
>程序退出时使用ctrl c删除临时文件(不工作)
.
#!/usr/bin/perl -l use warnings; use strict; use File::Temp qw(tempfile tmpfile); my $fh = File::Temp->new; close $fh; -f "$fh" || die "$fh does not exist"; print "hit enter and the file will be deleted"; print "hit ctrl+c and it won't"; print "verify with ls $fh after program exits"; readline STDIN;
编辑1
我测试了tempfile的行为.它似乎证实Linux支持我正在寻找的东西(将文件标记为临时/取消链接打开文件).我似乎有某种理想化的File :: Temp.
# program will die because os deletes tmpfile after close my $fh = tempfile; close $fh; stat $fh || die; readline STDIN;
解决方法
要使Control_C键盘中断运行END块,您需要添加信号处理程序.比较以下行为:
perl -E 'END{say "END"};<STDIN>'
有:
perl -E '$SIG{INT}=sub{die};END{say "END"};<STDIN>'
An END code block is executed as late as possible,that is,after perl has finished running the program and just before the interpreter is being exited,even if it is exiting as a result of a die() function. (But not if it's morphing into another program via exec,or being blown out of the water by a signal--you have to trap that yourself (if you can).)