2015-02-24 81 views
0

我想分析rsyslog日誌。爲此,我將所有日誌發送給socat,然後將它們發送到Unix域套接字。該套接字是通過perl腳本創建的,該腳本正在該套接字上偵聽以解析日誌。無法使用socat連接到套接字

我的bash腳本到rsyslog現在正在發送的所有日誌

if [ ! `pidof -x log_parser.pl` ] 
    then 
./log_parser.pl & 1>&1 
fi 

if [ -S /tmp/sock ] 
then 
/usr/bin/socat -t0 -T0 - UNIX-CONNECT:/tmp/sock 2>> /var/log/socat.log 
fi 

/tmp/sock使用perl腳本log_parser.pl這是

use IO::Socket::UNIX; 

sub socket_create { 
    $socket_path = '/tmp/sock'; 
    unlink($socket_path); 

    $listner = IO::Socket::UNIX->new(
     Type => SOCK_STREAM, 
     Local => $socket_path, 
     Listen => SOMAXCONN, 
     Blocking => 0, 
    ) 
     or die("Can't create server socket: $!\n"); 

    $socket = $listner->accept() 
     or die("Can't accept connection: $!\n"); 
    } 

    socket_create(); 
    while(1) { 

    chomp($line=<$socket>); 
    print "$line\n"; 
    } 

有這個錯誤我是從socat是

越來越創建
2015/02/24 11:58:01 socat[4608] E connect(3, AF=1 "/tmp/sock", 11): Connection refused 

我不是插座的冠軍所以ia米不能理解這是什麼。請幫忙。提前致謝。

主要問題是,當我殺了我的perl腳本,然後bash腳本是想要再次調用它並啓動它。 究竟發生了什麼是sript開始,但socat不是開始,而是它給這個錯誤,永遠不會開始。

+0

你正在定義一個子程序,但是你在哪裏調用它? – reinierpost 2015-02-24 09:01:21

回答

1

如果我在嘗試使用socat之前沒有運行perl程序,我可以複製你的錯誤。下面是我的什麼作品:

1)my_prog.pl:

use strict; 
use warnings; 
use 5.016; 
use Data::Dumper; 
use IO::Socket::UNIX; 

my $socket_path = '/tmp/sock'; 
unlink $socket_path; 

my $socket = IO::Socket::UNIX->new(
    Local => $socket_path, 
    Type => SOCK_STREAM, 
    Listen => SOMAXCONN, 
) or die "Couldn't create socket: $!"; 

say "Connected to $socket_path..."; 
my $CONN = $socket->accept() 
    or die "Whoops! Failed to open a connection: $!"; 

{ 
    local $/ = undef; #local -> restore previous value when the enclosing scope, delimited by the braces, is exited. 
         #Setting $/ to undef puts file reads in 'slurp mode' => whole file is considered one line. 
    my $file = <$CONN>; #Read one line. 
    print $file; 
}` 

2)$ perl my_prog.pl

3)socat -u -v GOPEN:./data.txt UNIX-CONNECT:/tmp/sock

-u和-v選項是沒有必要的:

-u   Uses unidirectional mode. The first address is only used for 
       reading, and the second address is only used for writing (exam- 
       ple). 


-v   Writes the transferred data not only to their target streams, 
       but also to stderr. The output format is text with some conver- 
       sions for readability, and prefixed with "> " or "< " indicating 
       flow directions. 

4)你也可以這樣做:

cat data.txt | socat STDIN UNIX-CONNECT:/tmp/sock 

管理標準輸出cat命令socat,然後列出STDIN作爲socat的文件之一。

迴應評論:

這個bash腳本爲我的作品:

#!/usr/bin/env bash 

echo 'bash script' 

../pperl_programs/my_prog.pl & 
sleep 1s 

socat GOPEN:./data.txt UNIX-CONNECT:/tmp/sock 

它看起來像Perl腳本沒有足夠的時間來建立套接字之前socat試圖傳輸數據。

+0

是的,我知道這個錯誤出現在我試圖在程序之前運行socat的時候。在我的bash腳本中,你可以看到如果perl程序沒有運行,它會嘗試運行它,然後去找socat。所以理想情況下,這個錯誤不應該到來,但這仍然會到來,我不知道爲什麼它會到來。 – shivams 2015-02-24 10:31:48

+0

@srtfmx,請參閱我的回答結束回覆。 – 7stud 2015-02-24 11:07:19

+0

謝謝。它適合我。一段時間以來,我一直在盯着它,這就是這個睡眠問題。非常感謝 :) – shivams 2015-02-24 11:28:28

相關問題