Bash脚本:等待apache2优雅停止

时间:2014-01-27 19:51:02

标签: apache bash ubuntu

在Ubuntu 12.04服务器上,我有一个bash脚本来优雅地停止我的apache2服务器,删除/var/www的内容,解压缩新内容并再次启动apache。 (一切都以root身份执行)

echo "Test";
cd /var;
service apache2 graceful-stop;
rm -R www/ && echo "Flush...";
unzip transfer.zip > /dev/null && echo "Flushed.";
service apache2 start;

我得到的错误是apache再次启动时:

Test
Flush...  
Flushed.
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
Action 'start' failed.
The Apache error log may have more information.

因此脚本不会等待apache停止。

这是我到目前为止所尝试的内容:

我试图等待wait(同样的错误。)

service apache2 graceful-stop;  
wait $!;

我试图获取apache的PID并等待这个(相同的错误)

pid=$(cat /var/run/apache2.pid)
apache2ctl graceful-stop;
wait $pid;

我尝试使用apache2ctl graceful-stop代替service apache2 graceful-stop(同样的错误)

<小时/> 我错过了什么?当我使用service apache2 stop时,一切正常:

 * Stopping web server apache2                                                                                        
... waiting                                                                                                  [ OK ]
Flush...
Flushed.
 * Starting web server apache2                                                                                [ OK ]

由于

修改

此处输出的退出代码为wait:

 * Stopping web server apache2                                                                                [ OK ]
0
Flush...
Flushed.
 * Starting web server apache2                                                                                       
(98)Address already in use: make_sock: could not bind to address 0.0.0.0:80
no listening sockets available, shutting down
Unable to open logs
Action 'start' failed.
The Apache error log may have more information.
                                                                                                              [fail]

1 个答案:

答案 0 :(得分:1)

似乎Apache本身建议在重启之间等待几秒钟: http://wiki.apache.org/httpd/CouldNotBindToAddress

实际上相对常见的是,释放和绑定到端口不是立即的。内核可能需要一些时间(最多几分钟)才能释放已关闭的套接字。它被称为灵儿时间。一些Apache文档也对此进行了简要讨论,请参阅http://httpd.apache.org/docs/2.2/misc/perf-tuning.html搜索“Lingering Close”。

关于此问题的问题有一个非常详细的答案:Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?