我有一個腳本,我用它檢查存儲在我的hosts.allow文件中的IP地址,以反映什麼IP映射到我的dyndns主機名,這樣我就可以登錄到我的服務器,一旦我同步我的當前IP到那主機名。出於某種原因,儘管腳本似乎會造成真正的間歇性問題。替換丟棄字符
我的hosts.allow文件中我有這樣一段:
#SOme.gotdns.com
sshd : 192.168.0.1
#EOme.gotdns.com
#SOme2.gotdns.com
sshd : 192.168.0.2
#EOme2.gotdns.com
我有一個cron運行的腳本(每分鐘),看起來像這樣:
#!/usr/bin/php
<?php
$hosts = array('me.gotdns.com','me2.gotdns.com');
foreach($hosts as $host)
{
$ip = gethostbyname($host);
$replaceWith = "#SO".$host."\nsshd : ".$ip."\n#EO".$host;
$filename = '/etc/hosts.allow';
$handle = fopen($filename,'r');
$contents = fread($handle, filesize($filename));
fclose($handle);
if (preg_match('/#SO'.$host.'(.*?)#EO'.$host.'/si', $contents, $regs))
{
$result = $regs[0];
}
if($result != $replaceWith)
{
$newcontents = str_replace($result,$replaceWith,$contents);
$handle = fopen($filename,'w');
if (fwrite($handle, $newcontents) === FALSE) {
}
fclose($handle);
}
}
?>
問題我的是間歇性字符正在被丟棄(我假設替換過程中),導致未來的更新失敗,因爲它插入類似的東西:
#SOme.gotdns.com
sshd : 192.168.0.1
#EOme.gotdn
注意失蹤「s.com」
當然,這意味着我失去了對服務器的訪問,任何想法,爲什麼這會發生?
謝謝。
你確定兩個腳本不會在同一時間運行? – RageZ 2011-12-21 10:33:05
你的意思是在第一個實例完成之前再次運行相同的腳本嗎? – robjmills 2011-12-21 10:42:52
是的,因爲腳本使用相同的文件進行讀寫,所以同時運行的兩個進程可能會產生一些有趣的結果。 – RageZ 2011-12-21 10:44:41