Qt生成程序设置为Linux服务,不能启动问题

利用库函数 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();

从此,我们能在守护进程中,愉快地使用Qt模块了。Oh ,yeah!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值