2015-05-11 80 views
1

有沒有什麼方法可以在PHP中測試fileHandle資源是否仍然指向它打開的文件系統中的文件?例如在此代碼:如何檢查文件句柄是否仍然指向文件

<?php 

$filename = './foo.txt'; 
$fileHandle = fopen($filename, 'c'); 

$unlinked = unlink($filename); 

if (!$unlinked) { 
    echo "Failed to unlink file."; 
    exit(0); 
} 

file_put_contents($filename, "blah blah"); 

// The file $filename will exist here, but I want to check that 
// the $fileHandle still points to the file on the filesystem name $filename. 
?> 

在代碼的結束,該文件句柄仍然存在,但不再引用文件系統上的文件「./foo.txt」。它仍然保留對已被解除鏈接的原始文件的引用,即它在文件系統中沒有活動條目,並且將數據寫入fileHandle不會影響名爲$ filename的文件的內容。

是否有一個(最好是原子)操作來確定$ fileHandle現在'無效',因爲它不再指向原始文件?

回答

0

這不是原子操作,但在Linux(和其他Unix系統)上,可以使用文件名stat和fileHandle上的fstat來檢查,並比較每個函數返回的inode。

這不適用於Windows,這不是最佳選擇。

<?php 

$filename = './foo.txt'; 
$fileHandle = fopen($filename, 'c'); 
$locked = flock($fileHandle, LOCK_EX|LOCK_NB, $wouldBlock); 

if (!$locked) { 
    echo "Failed to lock file."; 
    exit(0); 
} 

$unlinked = unlink($filename); 

if (!$unlinked) { 
    echo "Failed to unlink file."; 
    exit(0); 
} 

// Comment out the next line to have the 'file doesn't exist' result. 
file_put_contents($filename, "blah blah "); 

$originalInode = null; 
$currentInode = null; 

$originalStat = fstat($fileHandle); 
if(array_key_exists('ino', $originalStat)) { 
    $originalInode = $originalStat['ino']; 
} 


$currentStat = @stat($filename); 
if($currentStat && array_key_exists('ino', $currentStat)) { 
    $currentInode = $currentStat['ino']; 
} 

if ($currentInode == null) { 
    echo "File doesn't currently exist."; 
} 
else if ($originalInode == null) { 
    echo "Something went horribly wrong."; 
} 
else if ($currentInode != $originalInode) { 
    echo "File handle no longer points to current file."; 
} 
else { 
    echo "inodes apparently match, which should never happen for this test case."; 
} 

$closed = fclose($fileHandle); 

if (!$closed) { 
    echo "Failed to close file."; 
    exit(0); 
} 
相關問題