这一次让我很难过,所以在经过这么多长时间的咖啡之后,我正在接触到我所知道的最好的编码社区,以及多喝咖啡。
基本上我需要一个perl脚本来等待文件在服务器上不再存在,然后再继续。真的在等待所有屏幕会话终止(/ var / run / screen是一个空目录)。
#!/usr/bin/perl
my $directory="/root/screens";
opendir(DIR, $directory) or die "couldn't open $directory: $!\n";
my @files = readdir DIR;
closedir DIR;
foreach (@files){
while (-e $_) {
print "$directory has $_ existing\n";
sleep 1;
}
}
Ex Dir。
total 8
drwxr-xr-x. 2 root root 4096 Oct 11 22:58 ./
drwxr-x---. 17 root root 4096 Oct 11 05:33 ../
-rw-r--r--. 1 root root 0 Oct 11 22:58 S-root
-rw-r--r--. 1 root root 0 Oct 11 22:58 S-root1
上述内容显然不起作用,但我只是没有在Google上看到这样做的好方法,而且这是漫长的一天。
答案 0 :(得分:2)
#!/usr/bin/perl
my $directory="./test";
my $no_empty = 1;
my @files = ();
while( $no_empty) {
opendir(DIR, $directory) or die "couldn't open $directory: $!\n";
@files = readdir DIR;
#print @files;
if(scalar @files == 2) {
$no_empty = 0;
last; ##directory is empty
} else {
print "Below files present--";
@files = grep {$_ !~ /\.{1,2}$/} @files; ## skip . (current dir) and parent dir (..)
print join (', ',@files); ##comma seperated file list
print "\n"; ##mendetory to flash the output buffer
sleep 1;
}
}
print "Start with processing cz dir is empty"
示例运行 -
> Below files present--def, abc
> Below files present--def, abc
> Below files present--def, abc
> Below files present--def, abc
> Start with processing cz dir is empty
答案 1 :(得分:0)
我想只要目录不为空,就需要执行while
循环。目标目录为空后,程序将返回。
让我们创建一个子例程来检查目标目录是否为空:
sub isDirEmpty {
my ($dir) = @_;
my $file;
if (opendir my $DFH, $dir) {
while ( defined ( $file = readdir $DFH) ) {
next if $file eq '.' or $file eq '..';
closedir $DFH;
return 0; #Not Empty
}
closedir $DFH;
return 1; #Empty
} else {
return -1; #Doesn't exist
}
}
无限循环的小测试:
my $targetDir = "/path/to/target/dir";
while (1) {
my $result = isDirEmpty($targetDir);
if ($result eq 1) {
print "Your directory is empty\n";
last;
} elsif ($result eq -1) {
print "There has been an error! please check your lousy code!\n";
}
}
瞧!
答案 2 :(得分:0)
怎么样:
my $directory="/root/screens";
while(<$directory/*>) {
say "not empty";
sleep 1;
}
答案 3 :(得分:0)
#!/usr/bin/perl
my $directory = "/root/screens";
while(1) {
my @files = <$directory/*>;
if($#files == -1) {
last;
} else {
sleep 1;
}
}
# do some stuff when the directory is empty
答案 4 :(得分:0)
#!/usr/bin/perl
my $directory="/root/screens";
opendir(DIR, $directory) or die "couldn't open $directory: $!\n";
@files = readdir DIR;
closedir DIR;
while (@files > 2) ### If @files have more than 2 items.
{
opendir(DIR, $directory) or die "couldn't open $directory: $!\n";
@files = readdir DIR;
closedir DIR;
sleep (1);
}
print "Directory is now empty and loop has ended";
请注意@files总是有2个项目,因为总会有./和../