2008-10-29 68 views

回答

2

雖然它消耗了其他用途的線路,但我已經編寫了代碼,它本質上就是這樣做的。

所有你需要做的就是記錄字節偏移量(與告訴)和inode(與統計)爲每個文件尾完成後。下一次對文件運行時,首先再次檢查inode(使用stat)。如果inode已經改變或文件小於記錄的偏移量,那麼它是一個不同的文件(刪除並重新創建,日誌被旋轉等),所以你應該從頭開始顯示它;否則,設置爲記錄的偏移量並從那裏顯示。

2

since正是這麼做雖然是C.

+0

你可以剛剛編輯你的問題。 – Axeman 2008-10-30 05:22:46

2

可能是這樣的Perl包可以幫助您:

File::Tail::Multi

從MultiTail派生,這Perl庫可以很容易地尾動態文件列表和匹配/使用完整正則表達式的行除外,甚至在本地維護它們的狀態。

示例使用File :: Tail :: Multi;

$tail1=File::Tail::Multi->new ( OutputPrefix => "f", 
           Debug => "$True", 
           Files => ["/var/adm/messages"] 
          ); 
while(1) { 
    $tail1->read; 
    # 
    $tail1->print; 
    sleep 10; 
} 
  • $tail1=File::Tail::Multi->new:創建新PTAIL對象
  • Files =>尾文件/ var/ADM /消息
  • OutputPrefix =>前置中對象屬性的每個線的文件開頭的名稱「LineArray 「
  • $tail1->read:從文件中讀取所有行
  • $tail1->print:打印對象屬性」LineArray「中的所有行;
+0

這是*得到*是perl的答案! – Axeman 2008-10-30 05:29:00

2

我實現的純Perl版本最低版本:

#! /usr/bin/perl 
# Perl clone of since(1) 
# http://welz.org.za/projects/since 
# 

use strict; 
use warnings; 

use Fcntl qw/ SEEK_SET O_RDWR O_CREAT /; 
use NDBM_File; 

my $state_file = "$ENV{HOME}/.psince"; 

my %states; 
tie(%states, 'NDBM_File', $state_file, O_CREAT | O_RDWR, 0660) 
     or die("cannot tie state to $state_file : $!"); 

while (my $filename = shift) { 
     if (! -r $filename) { 
       # Ignore 
       next; 
     } 
     my @file_stats = stat($filename); 
     my $device = $file_stats[0]; 
     my $inode = $file_stats[1]; 
     my $size = $file_stats[7]; 
     my $state_key = $device . "/" .$inode; 
     print STDERR "state_key=$state_key\n"; 

     if (! open(FILE, $filename)) { 
       print STDERR "cannot open $filename : $!"; 
       next; 
     } 

     # Reverting to the last cursor position 
     my $offset = $states{$state_key} || 0; 
     if ($offset <= $size) { 
       sysseek(FILE, $offset, SEEK_SET); 
     } else { 
       # file was truncated, restarting from the beginning 
       $offset = 0; 
     } 

     # Reading until the end 
     my $buffer; 
     while ((my $read_count = sysread(FILE, $buffer, 4096)) > 0) { 
       $offset += $read_count; 
       print $buffer; 
     } 
     # Nothing to read 
     close(FILE); 
     $states{$state_key} = $offset; 
} 

# Sync the states 
untie(%states); 

@戴夫:這幾乎就像你的算法,但我不使用告訴,但內部保持計數器。