利用库函数 daemon()创建守护进程
daemon() 其函数原型:
#include <unistd.h>
int daemon(int nochdir, int noclose);
DESCRIPTION
The daemon() function is for programs wishing to detach themselves
from the controlling terminal and run in the background as system
daemons.
If nochdir is zero, daemon() changes the process's current working
directory to the root directory ("/"); otherwise, the current working
directory is left unchanged.
If noclose is zero, daemon() redirects standard input, standard
output and standard error to /dev/null; otherwise, no changes are
made to these file descriptors.
RETURN VALUE
(This function forks, and if the fork(2) succeeds, the parent calls
_exit(2), so that further errors are seen by the child only.) On
success daemon() returns zero. If an error occurs, daemon() returns
-1 and sets errno to any of the errors specified for the fork(2) and
setsid(2).
在main函数开始处加入,以下代码段:
if(-1 == daemon(0, 0))
{
printf("daemon error\n");
exit(1);
}
然并卵,这些还不够
本以为这样,就能开开心地用Qt写个标准的Linux服务守护(daemon)进程,结果我的确是想多了。用Qt Ftp写的个服务,一启动就崩溃,搞得人也无比崩溃。痛定思痛,头发都抓掉了好几把后,终于知道少了点啥东东。
用一个Qt Widgets Application Demo揭开谜底
#include "mainwindow.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
看到上面的代码,大家是不是有点眉目了。每个Qt GUI应用都有个QApplication,帮助文档原文如下:
QApplication Class
The QApplication class manages the GUI application's control flow and main settings. More...
Header:
#include <QApplication>
qmake:
QT += widgets
Inherits:
QGuiApplication
作为守护进程当然也有个类似的东东——QCoreApplication
,帮助文档原文如下:
QCoreApplication Class
The QCoreApplication class provides an event loop for Qt applications without UI. More...
Header:
#include <QCoreApplication>
qmake:
QT += core
Inherits:
QObject
在守护进程main末尾,加入QCoreApplication
代码片段如下:
QCoreApplication a(argc, argv);
//业务代码
return a.exec();