我有一个子例程,其中我试图专门锁定一组文件(一次一个),并保持一定的给定时间(通过sleep)的锁定。我试图添加让用户在按下某个键(如回车键)时解锁当前锁定(睡眠)文件的功能。我只是不确定要采取什么方向来实现这一目标。每次尝试使用STDIN并检查\ n都无效。谢谢。从输入文件锁定和解锁
下面是子程序。我切换到我想要这些文件的目录。从1创建文件以指定多少个文件。对于每个文件,放置一个独占锁,然后休眠指定的时间量。
编辑:这是我的错,没有提到这个,但是,这个脚本将在Windows环境中运行。我最好喜欢一个不需要附加模块安装但不包含在Perl中的解决方案。 (这是因为breq中的模块解决方案不支持Windows)。谢谢。
sub lockFiles{
#creates files that are locked for a specific amount of seconds.
chdir("lock files")or die "Unable to enter dir $!\n";
opendir(DIR,".") or die "Can't open the current directory: $!\n";
#file iterator
my $i=1;
#for each file lock it and sleep the given amount of time
while($i<=$numberOfFiles){
open FILE, ">>", "test$i.txt" or die $!;
flock(FILE, 2) or die "Could not lock test$i.txt\n";
print "test$i.txt locked, locking for $timeToSleep seconds\n";
print "Press ctrl+c to kill this\n";
sleep($timeToSleep);
$i++;
close(FILE);
}
closedir(DIR);
#change back to the parent folder
chdir("..") or die "Can't change to the directory: $!\n";
print "subRoutine lockFiles success\n";
}
抱歉,延迟响应,但它看起来像它的工作。我只是把一个'回报'在内部while循环中,所以当它检测到一个键时,它会退出你的子程序,返回到我的程序并关闭(解锁)文件。谢谢你的帮助。 – iCanHasFay