【问题标题】:Is there a way in Perl to tell if a Perl process in Windows is using a specific file?Perl 中有没有办法判断 Windows 中的 Perl 进程是否正在使用特定文件?
【发布时间】:2013-12-12 04:13:08
【问题描述】:

背景资料:

我有一个 Perl 脚本转换为一个 EXE 文件 script.exe,它在 Windows 上运行。 Script.exe 有时会从配置文件 config.ini 读取和更新。

Script.exe 使用指定config.ini 文件位置的命令行参数执行。或者它可以在没有命令行参数的情况下运行,并将默认为 config.ini 文件的默认位置。

目标:

防止 script.exe 使用同一个 config.ini 文件多次执行。

我该怎么做?

【问题讨论】:

  • 是我读错了,还是您只是在寻找flock
  • flock 在 windows 下工作吗?
  • @mpapec,是的,虽然它创建强制锁而不是建议锁
  • 或许perl可以从Process Explorer stackoverflow.com/questions/15708/…读取
  • @ikegami 好的,所有组合都有效吗?不包括/共享 |阻塞/非阻塞?

标签: perl activestate windows-process


【解决方案1】:

在配置文件中使用flock

use Fcntl qw( LOCK_EX LOCK_NB );

open(my $config_fh, '<', $config_qfn)
   or die("Can't open config file \"$config_qfn\": $!\n");

if (!flock($config_fh, LOCK_EX | LOCK_NB)) {
   if ($!{EWOULDBLOCK}) {
      die("Config file $config_qfn already in use\n");
   }

   die("Error trying to lock the config file: $!\n");
}

... # Rest of program. Don't close $config_fh

【讨论】:

  • 他想防止多个PID使用相同的配置,所以LOCK_EX似乎是正确的选择。
  • @mpapec,Herp derp。固定。
  • @mpapec,man 2 flock。您可能还想查看 perlvar 中的 %!
  • +1。好的,所以关于 ext3/linux 上的群发的所有东西都可以移植到 win 上?
猜你喜欢
  • 2014-02-09
  • 1970-01-01
  • 1970-01-01
  • 2011-04-15
  • 1970-01-01
  • 2010-09-22
  • 2012-02-05
  • 2011-02-05
  • 1970-01-01
相关资源
最近更新 更多