Kill all close wait process

We have seen many cases where the client didn’t close the connection correctly, the process is stuck at CLOSE_WAIT status, i never clear the database connection. We have this script to kill all close_wait connection.

<?
//Some apache process are in close_wait
//replace apache2 with other stuff (httpd..)
$cmd="netstat -ntp | grep CLOSE_WAIT | grep apache2";
$process_array=array("httpd","apache2");
$hostname=trim(shell_exec("hostname -s"));
if($hostname=='ubuntu')
$cmd="netstat -ntp ";
debug("Running $cmd");
$netstat=shell_exec($cmd);
$file_log="/tmp/kill_close_wait.txt";

$arr=explode("\n",$netstat);
//print_r($arr);
$test=false;//if we are debugging- if we are debug - it will not killl
$log=false;
foreach($arr as $line)
{
$line=preg_replace('/\s{2,}/',' ', $line);
$arr2=explode(' ',$line);
if(isset($arr2[6]) && $arr2[6]<>'-')
{
//print_r($arr3);
$arr3=explode('/',$arr2[6]);
$process_id=$arr3[0];

if($process_id==0)
continue;
$process_name=$arr3[1];
if(!in_array($process_name,$process_array))
continue;

debug("Found: $line: with process_id: $process_id");
$cmd="kill $process_id";
if(!$test)
{

debug("Kill $cmd");
shell_exec("$cmd");
$log=true;
}else
{
debug("Test - not kill : $cmd");
}

}

}

if($log)
{
$content="--------------------------------------------".date("Y-m-d H:i:s")."-------------------------------------------------------- \r\n $netstat";
write_file($file_log,$content);

}

function debug($s)
{
echo "\r\n $s";
}
function write_file($filename,$content)
{
$fp = fopen($filename, 'a+');

fwrite($fp, $content);
fclose($fp);
}
?>

 

Leave a Reply

Your email address will not be published. Required fields are marked *