shell中通过mongo args &的方式启动mongo进程,退出shell重新登进之后发现mongo进程没了,查看日志发现有如下输出:
2015-06-18T18:39:58.593+0800 [signalProcessingThread] got signal 1 (Hangup), will terminate after current cmd ends
2015-06-18T18:39:58.593+0800 [signalProcessingThread] now exiting
2015-06-18T18:39:58.593+0800 [signalProcessingThread] dbexit:
2015-06-18T18:39:58.593+0800 [signalProcessingThread] shutdown: going to close listening sockets…
2015-06-18T18:39:58.593+0800 [signalProcessingThread] closing listening socket: 8
2015-06-18T18:39:58.593+0800 [signalProcessingThread] closing listening socket: 10
2015-06-18T18:39:58.593+0800 [signalProcessingThread] removing socket file: /tmp/mongodb-27017.sock
2015-06-18T18:39:58.593+0800 [signalProcessingThread] shutdown: going to flush diaglog…
2015-06-18T18:39:58.593+0800 [signalProcessingThread] shutdown: going to close sockets…
2015-06-18T18:39:58.593+0800 [signalProcessingThread] shutdown: waiting for fs preallocator…
2015-06-18T18:39:58.593+0800 [signalProcessingThread] shutdown: lock for final commit…
2015-06-18T18:39:58.593+0800 [signalProcessingThread] shutdown: final commit…
2015-06-18T18:39:58.603+0800 [replslave] repl: AssertionException dbclient error communicating with server: 172.19.2.176:27017
2015-06-18T18:39:58.615+0800 [signalProcessingThread] shutdown: closing all files…
2015-06-18T18:39:58.642+0800 [signalProcessingThread] closeAllFiles() finished
2015-06-18T18:39:58.642+0800 [signalProcessingThread] journalCleanup…
2015-06-18T18:39:58.642+0800 [signalProcessingThread] removeJournalFiles
2015-06-18T18:39:58.643+0800 [signalProcessingThread] shutdown: removing fs lock…
2015-06-18T18:39:58.643+0800 [signalProcessingThread] dbexit: really exiting now
可以看到有其他进程给mongo发了Hangup信息,就如同kill -1 pid
,但可以确认的是没有人手动信号给mongodb进程,google之后发现这篇文章
原因大致如下:
Bash resends a SIGHUP to all jobs if it receives a SIGHUP itself; this would include mongod.
Also, if you happen to have huponexit turned on, every job will receive a SIGHUP when bash exits.
https://www.gnu.org/software/bash/manual/html_node/Signals.html
原来我用shell登进之后启动了mongo,然后退出shell使用的方式是直接关掉窗口,linux认为这是一起异常退出,这样一来这个shell进程就会收到SIGHUP信号,为了保证状态一致性,从而给它的所有子进程发送SIGHUP信号.而使用命令exit退出就不会有这种问题,因为linux会认为这是一种正常的退出
那么如何避免这种问题呢? 直接关闭窗口可能是很多人的习惯了(陋习),所以我们不能要求linux管理员总是这样做,是人就有可能会犯错,应该从根本上解决这个问题
查看mongodb官方文档会发现mongo有–fork这样的一个参数,使用该参数启动mongo时,会自动将其挂到init进程(pid为1)下启动,而不加的话ppid(父进程id)就是当前的shell进程,所以只要加上–fork问题就引刃而解了,这里需要注意的是,所有需要在后台运行的程序都需要注意该情况,务必采用像mongo –fork的方式执行
关于Linux的signal(信号)和bash更多内容请自行关注man bash