Perl:撤消取消与文件打开的链接

Perl: Undo unlink with file open

unlink 不删除打开的文件;它只是删除名称和名称的 link 。 unlink 可以撤消吗?

open(my $fh, ">", undef) || die;
print $fh "foo";
# This does not work
link($fh,"/tmp/bar") || die;

未linked 文件的打开文件句柄可以linked 到文件吗?

如果可行,您可以将打开模式 ('>') 更改为 read/write。然后,当您需要恢复文件时,您可以使用文件句柄将其打印到新打开的文件中,如果需要,甚至可以使用相同的文件名。

open my $fh, '+>', $file;
say $fh "line 1";
unlink $file;
say $fh "more lines";

seek $fh, 0, 0;
open my $fh_rec, '>', $file   or die "Can't open $file (again): $!";
print $fh_rec $_ while <$fh>;

这不完全是要求的,但它恢复了文件内容和访问权限 给它。进一步打印到 $fh 会使新的 $file 不同步,所以这可以在写入完成时完成(恢复文件)或将打印切换到 $fh_rec(然后也是 close $fh).


恢复文件的另一种方法是使用 OS,如果它使用 /proc 并公开文件句柄。然后可以从/proc/PID/fd/N复制数据。要识别 N,可以用 ls -l 扫描 fd/(少数)中的所有链接,因为删除的文件名称后应该有 (deleted)

此外,lsof -p PID 列出给定进程的所有打开文件描述符。已删除文件的文件有 (deleted)。 (lsof +L1 -p PID 仅输出已删除的条目,但仍然不少。)从该输出中,我们可以读取该文件描述符,然后从 /proc/PID/fd/N 复制数据。这样我们也得到了inode号,也可以用来恢复文件。

这些答案说:'No, not in general, and definitely not on all Unices':

Relinking an anonymous (unlinked but open) file

https://serverfault.com/questions/168909/relinking-a-deleted-file

从打开的文件句柄复制内容可能有效。