Beispiel #1
0
/*!
 * Attempts to register the service on the local network.
 *
 * If noAutoRename is set to true, registration will fail if another service of the same service type
 * is already registered with the same service name. Otherwise, the service name will be updated with
 * a number to make it unique.
 *
 * \sa registered
 * \sa registrationError
 */
void QxtDiscoverableService::registerService(bool noAutoRename)
{
    if(state() != Unknown) {
        qWarning() << "QxtDiscoverableService: Cannot register service while not in Unknown state";
        emit registrationError(0);
        return;
    }

    QStringList subtypes = qxt_d().serviceSubTypes;
    subtypes.prepend(fullServiceType());

    DNSServiceErrorType err;
    err = DNSServiceRegister(&(qxt_d().service),
                             noAutoRename ? kDNSServiceFlagsNoAutoRename : 0,
                             qxt_d().iface,
                             serviceName().isEmpty() ? 0 : serviceName().toUtf8().constData(),
                             subtypes.join(",_").toUtf8().constData(),
                             domain().isEmpty() ? 0 : domain().toUtf8().constData(),
                             host().isEmpty() ? 0 : host().toUtf8().constData(),
                             qxt_d().port,
                             1, // must include null terminator
                             "",
                             QxtDiscoverableServicePrivate::registerServiceCallback,
                             &qxt_d());
    if(err != kDNSServiceErr_NoError) {
        qxt_d().state = Unknown;
        emit registrationError(err);
    } else {
        qxt_d().state = Registering;
        qxt_d().notifier = new QSocketNotifier(DNSServiceRefSockFD(qxt_d().service), QSocketNotifier::Read, this);
        QObject::connect(qxt_d().notifier, SIGNAL(activated(int)), &qxt_d(), SLOT(socketData()));
    }
}
bool QtServiceController::isRunning() const
{
    QtUnixSocket sock;
    if (sock.connectTo(socketPath(serviceName())))
	return true;
    return false;
}
Beispiel #3
0
/*!
 * Attempts to resolve the service in order to determine the host and port necessary to establish a connection.
 *
 * If forceMulticast is set to true, QxtDiscoverableService will use a multicast request to resolve the service,
 * even if the host name appears to be a unicast address (that is, outside the local network).
 *
 * \sa resolved
 * \sa resolveError
 */
void QxtDiscoverableService::resolve(bool forceMulticast)
{
    if(state() != Unknown && state() != Found) {
        qWarning() << "QxtDiscoverableService: Cannot resolve service while not in Unknown or Found state";
        emit resolveError(0);
        return;
    }

    DNSServiceErrorType err;
    err = DNSServiceResolve(&(qxt_d().service),
                            (forceMulticast ? kDNSServiceFlagsForceMulticast : 0),
                            qxt_d().iface,
                            serviceName().toUtf8().constData(),
                            fullServiceType().constData(),
                            domain().toUtf8().constData(),
                            QxtDiscoverableServicePrivate::resolveServiceCallback,
                            &qxt_d());
    if(err != kDNSServiceErr_NoError) {
        qxt_d().state = Unknown;
        emit resolveError(err);
    } else {
        qxt_d().state = Resolving;
        qxt_d().notifier = new QSocketNotifier(DNSServiceRefSockFD(qxt_d().service), QSocketNotifier::Read, this);
        QObject::connect(qxt_d().notifier, SIGNAL(activated(int)), &qxt_d(), SLOT(socketData()));
    }
}
Beispiel #4
0
bool checkDaemonExistence(const char* daemonName) 
{
    SingleLogger* logger = SingleLogger::InitLogger(); 
    std::string serviceName(daemonName);
    bool isRunning = false;
    std::string pidFileName("/var/run/" + serviceName + ".pid");
    std::ifstream pidFile(pidFileName.c_str(), std::ifstream::binary);
    if(pidFile.is_open())
    {
        long pid = 0;
        std::string pidLine;
        if (pidFile.is_open()) 
        {
            getline(pidFile, pidLine);
            pid = std::stoi(pidLine);
            kill(pid, 0);
            isRunning = !(errno == ESRCH);
        }
    }

    if (!isRunning) 
    {
        std::ofstream pidFile(pidFileName.c_str(), std::ofstream::binary);
        if (pidFile.is_open()) {
            pidFile << getpid();
            pidFile.close();
        }
        else
            logger->logMessage(SingleLogger::WARNING, "pid file is not created");
    } 
    else
        logger->logMessage(SingleLogger::ERROR, "daemon already running");

    return isRunning;
}
void QtServiceBase::logMessage(const QString &message, QtServiceBase::MessageType type,
			    int, uint, const QByteArray &)
{
    if (!d_ptr->sysd)
        return;
    int st;
    switch(type) {
        case QtServiceBase::Error:
	    st = LOG_ERR;
	    break;
        case QtServiceBase::Warning:
            st = LOG_WARNING;
	    break;
        default:
	    st = LOG_INFO;
    }
    if (!d_ptr->sysd->ident) {
	QString tmp = encodeName(serviceName(), TRUE);
	int len = tmp.toLocal8Bit().size();
	d_ptr->sysd->ident = new char[len+1];
	d_ptr->sysd->ident[len] = '\0';
	::memcpy(d_ptr->sysd->ident, tmp.toLocal8Bit().constData(), len);
    }
    openlog(d_ptr->sysd->ident, LOG_PID, LOG_DAEMON);
    foreach(QString line, message.split('\n'))
        syslog(st, "%s", line.toLocal8Bit().constData());
    closelog();
}
bool ShellCommandService::executeService(TasCommandModel& model, TasResponse& response)
{
    if(model.service() == serviceName() ){
        TasCommand* command = getCommandParameters(model, "shellCommand");
        if(command && !command->text().isEmpty()){
            if (command->parameter("detached") == "true"){
                detachedShellCommand(command->text(), response);
            }
            else if (command->parameter("threaded") == "true") {
                shellTask(command->text(), response);
            }
            else if (command->parameter("status") == "true") {
                TasCommand* command = getCommandParameters(model, "shellCommand");
                if(command && !command->text().isEmpty()){
                    qint64 pid = command->text().toInt();
                    if (command->parameter("kill") == "true") {
                        killTask(pid, response);
                    } else {
                        shellStatus(pid, response);
                    }
                }
            }
            else{
                shellCommand(command->text(), response);
            }
        }
        else{
            response.setErrorMessage(NO_COMMAND_TO_EXECUTE);
        }
        return true;
    }
    else{
        return false;
    }
}
Beispiel #7
0
bool RegisterService::executeService(TasCommandModel& model, TasResponse& response)
{
    if(model.service() == serviceName() ){
        TasCommand* command = getCommandParameters(model, COMMAND_REGISTER);
        if(command){
            ClientDetails client;
            bool ok;
            //this should not really ever fail (app pid used to generate in client side)
            quint64 clientPid = command->parameter(PLUGIN_ID).toULongLong(&ok); 
            client.processId = clientPid;
            client.processName = command->parameter(PLUGIN_NAME);
#ifdef Q_OS_SYMBIAN
            client.applicationUid = command->parameter(APP_UID);
#endif
            client.pluginType = command->parameter(PLUGIN_TYPE);
            client.socket = response.requester();
            registerPlugin(client);
        }
        else{
            command = getCommandParameters(model, COMMAND_UNREGISTER);
            if(command){
                unRegisterPlugin(*command);
            }
        }
        return true;
    }
    else{
        return false;
    }
}
// ----------------------------------------------------------------------------
// MsgErrorWatcher::~MsgErrorWatcher
// @see MsgErrorWatcher.h
// ----------------------------------------------------------------------------
void MsgErrorWatcher::ShowNote(TMsgErrorNoteIds errornoteid)
{
    QDEBUG_WRITE("MsgErrorWatcher::ShowNote : Enter")
    QDEBUG_WRITE_FORMAT("errornoteid : ", errornoteid)
    HbDeviceMessageBox messageBox(HbMessageBox::MessageTypeWarning);
    QAction* actionView = NULL;
    QAction* actionQuit = NULL;
    const QAction* result = NULL;
    //create dialog parameters
    QString text("");
    switch (errornoteid) {
    case EDiskLowNote1:
        text = LOC_MSG_ERRH_DISK_LOW_1;
        break;
    case EMemoryLowNote:
        text = LOC_MSG_ERRH_MEMORY_LOW;
        break;
    case ERoamingNote:
        text = LOC_MMS_OFF;
        break;
    case EInvalidAccessPointNote:
        text = LOC_MSG_ERRH_ACCESS_POINTS_INV;
        messageBox.setTimeout(HbPopup::NoTimeout);
        messageBox.setText(text);
        actionView = new QAction(LOC_OK, this);
        messageBox.setAction(actionView, HbDeviceMessageBox::AcceptButtonRole);

        actionQuit = new QAction(LOC_CANCEL, this);
        messageBox.setAction(actionQuit, HbDeviceMessageBox::RejectButtonRole);

        messageBox.setDismissPolicy(HbPopup::NoDismiss);
        // launch Messagebox
        result = messageBox.exec();

        // if accepted launch view else quit
        if (messageBox.isAcceptAction(result)) {
            QList<QVariant> args;
            QString serviceName("messagesettings");
            QString operation("launchSettings(int)");
            XQAiwRequest* request;
            XQApplicationManager appManager;
            request = appManager.create(serviceName, "com.nokia.symbian.IMessageSettings",
                operation, false); // non embedded
            if (request == NULL) {
                return;
            }
            args << QVariant(MsgSettingsView::MMSView);
            request->setArguments(args);
            request->send();
            delete request;
        }
        return;
    default:
        break;
    }
    HbDeviceNotificationDialog::notification("", text);
    QDEBUG_WRITE("MsgErrorWatcher::ShowNote : Exit")

}
bool QtServiceController::uninstall()
{
    QSettings settings(QSettings::SystemScope, "QtSoftware");
    settings.beginGroup("services");

    settings.remove(serviceName());

    settings.endGroup();
    settings.sync();

    QSettings::Status ret = settings.status();
    if (ret == QSettings::AccessError) {
        fprintf(stderr, "Cannot uninstall \"%s\". Cannot write to: %s. Check permissions.\n",
                serviceName().toLatin1().constData(),
                settings.fileName().toLatin1().constData());
    }
    return (ret == QSettings::NoError);
}
bool ObjectService::executeService(TasCommandModel& model, TasResponse& response)
{
    if(model.service() == serviceName() ){
        performObjectService(model, response);
        return true;
    }
    else{
        return false;
    }
}
/*!
  Passes service directed to plugins on to the correct plugin.
 */
bool InfoService::executeService(TasCommandModel& model, TasResponse& response)
{
    if(model.service() == serviceName() ){
        mLogger->performLogService(model, response);   
        return true;
    }    
    else{
        return false;
    }
}
Beispiel #12
0
void Master::executeInterruptionList()
{
	int i = 0;
	for(Linterrupt::interator n = interruptions.begin(); n != interruptions.end(); ++n)
	{
		//pegando o nome do servico
		string serviceTemp = n->getService();
		char *service = new char [serviceTemp.length()+1];
  		strcpy (service, serviceTemp.c_str());
		char *name = strtok(service, "/");
		string serviceName(name, strlen(name)+1);
		if(inNodeList(serviceName))
		{
			for(Lnode::interator n = nodes.begin(); n != nodes.end(); ++n)
			{
				if(n->getName().compare(serviceTemp))
				{
					n->runService(serviceTemp);
				}
			}
			Node *temp = n;
			interruptions.remove(n);
			detroy(temp);
			continue;
		}
		if(inSuperNodeList(serviceName))
		{
			for(Lsnode::interator n = sNodes.begin(); n != sNodes.end(); ++n)
			{
				if(n->getName().compare(serviceTemp))
					n->runService(serviceTemp);
			}
			Node *temp = n;
			interruptions.remove(n);
			detroy(temp);
			continue;
		}

		int temp = inConnectionList(serviceName);
		if(temp >= 0)
		{
			for(Lconection::interator n = connections.begin(); n != connections.end(); ++n)
			{	
				if(temp == i)
					n->sendMessage(serviceTemp);
				i++;
			}
			Node *temp = n;
			interruptions.remove(n);
			detroy(temp);
		}
	}
}
QString QtServiceController::serviceFilePath() const
{
    QSettings settings(QSettings::SystemScope, "QtSoftware");
    settings.beginGroup("services");
    settings.beginGroup(serviceName());

    QString path = settings.value("path").toString();

    settings.endGroup();
    settings.endGroup();

    return path;
}
Beispiel #14
0
	Service(int argc, char **argv)
		: QtService<QCoreApplication>(argc, argv, "Elephant Service")
	{
		setServiceDescription("No description yet.");
		
		qApp->setApplicationName(serviceName());
		qApp->setOrganizationName("GKHY");
		qApp->setOrganizationDomain("www.gkhy.com.cn");


		setServiceFlags(QtService::Default);
		setStartupType(QtServiceController::AutoStartup);
	}
QtServiceController::StartupType QtServiceController::startupType() const
{
    QSettings settings(QSettings::SystemScope, "QtSoftware");
    settings.beginGroup("services");
    settings.beginGroup(serviceName());

    StartupType startupType = (StartupType)settings.value("startupType").toInt();

    settings.endGroup();
    settings.endGroup();

    return startupType;
}
QString QtServiceController::serviceDescription() const
{
    QSettings settings(QSettings::SystemScope, "QtSoftware");
    settings.beginGroup("services");
    settings.beginGroup(serviceName());

    QString desc = settings.value("description").toString();

    settings.endGroup();
    settings.endGroup();

    return desc;
}
Beispiel #17
0
QString KInetSocketAddress::pretty() const
{
    if(d->sockfamily != AF_INET
#ifdef AF_INET6
            && d->sockfamily != AF_INET6
#endif
      )
    {
        kdWarning() << "KInetSocketAddress::pretty() called on uninitialized class\n";
        return i18n("<empty>");
    }

    return i18n("1: hostname, 2: port number", "%1 port %2").arg(nodeName()).arg(serviceName());
}
/*******************************************************************************
**
** Function:        nativeLlcpSocket_doConnectBy
**
** Description:     Establish a connection to the peer.
**                  e: JVM environment.
**                  o: Java object.
**                  sn: Service name.
**
** Returns:         True if ok.
**
*******************************************************************************/
static jboolean nativeLlcpSocket_doConnectBy (JNIEnv* e, jobject o, jstring sn)
{
    ALOGD ("%s: enter", __FUNCTION__);

    PeerToPeer::tJNI_HANDLE jniHandle = (PeerToPeer::tJNI_HANDLE) nfc_jni_get_nfc_socket_handle(e, o);

    ScopedUtfChars serviceName(e, sn);
    if (serviceName.c_str() == NULL)
    {
        return JNI_FALSE;
    }
    bool stat = PeerToPeer::getInstance().connectConnOriented(jniHandle, serviceName.c_str());

    ALOGD ("%s: exit", __FUNCTION__);
    return stat ? JNI_TRUE : JNI_FALSE;
}
bool QtServiceController::isInstalled() const
{
    QSettings settings(QSettings::SystemScope, "QtSoftware");
    settings.beginGroup("services");

    QStringList list = settings.childGroups();

    settings.endGroup();

    QStringListIterator it(list);
    while (it.hasNext()) {
        if (it.next() == serviceName())
            return true;
    }

    return false;
}
bool ScreenshotService::executeService(TasCommandModel& model, TasResponse& response)
{
    if(model.service() == serviceName() ){
        TasLogger::logger()->debug("ScreenshotService::executeService in");
        QGuiApplication *app = qobject_cast<QGuiApplication*>(qApp);
        if(app){
            getScreenshot(model, response);
        }
        else{
            TasLogger::logger()->debug("ScreenshotService::executeService application has no ui!");
            response.setErrorMessage(NO_UI_ERROR);
        }
        return true;
    }
    else{
        return false;
    }
}
void OutQueueStatisticsWidget::updateStatistics(OutQueueStatistics& stats)
{
	static const int cellx = 6 ;
	static const int celly = 10+4 ;

	QPixmap tmppixmap(maxWidth, maxHeight);
	tmppixmap.fill(Qt::transparent);
	setFixedHeight(maxHeight);

	QPainter painter(&tmppixmap);
	painter.initFrom(this);

	maxHeight = 500 ;

	// std::cerr << "Drawing into pixmap of size " << maxWidth << "x" << maxHeight << std::endl;
	// draw...
	int ox=5,oy=5 ;

    painter.setPen(QColor::fromRgb(70,70,70)) ;
    //painter.drawLine(0,oy,maxWidth,oy) ;
    //oy += celly ;

    QString by_priority_string,by_service_string ;

    for(int i=1;i<stats.per_priority_item_count.size();++i)
        by_priority_string += QString::number(stats.per_priority_item_count[i]) + " (" + QString::number(i) + ") " ;

    for(std::map<uint16_t,uint32_t>::const_iterator it(stats.per_service_item_count.begin());it!=stats.per_service_item_count.end();++it)
        by_service_string += QString::number(it->second) + " (" + serviceName(it->first) + ") " ;

    painter.drawText(ox,oy+celly,tr("Outqueue statistics")+":") ; oy += celly*2 ;
    painter.drawText(ox+2*cellx,oy+celly,tr("By priority: ") + by_priority_string); oy += celly ;
    painter.drawText(ox+2*cellx,oy+celly,tr("By service : ") + by_service_string); oy += celly ;

    oy += celly ;

	// update the pixmap
	//
	pixmap = tmppixmap;
	maxHeight = oy ;
}
Beispiel #22
0
/*!
 * Returns the endpoint's full service name.
 *
 * The full service name is a human-readbale form.  For example, the full name for
 * the `cloudsearch` service is `Amazon CloudSearch`.  Likewise, the full name for
 * the `rds` service is `Amazon Relational Database Service`.
 *
 * \sa serviceName
 */
QString AwsEndpoint::fullServiceName() const
{
    return fullServiceName(serviceName());
}
bool QtServiceController::sendCommand(int code)
{
    return sendCmd(serviceName(), QString(QLatin1String("num:") + QString::number(code)));
}
bool QtServiceController::pause()
{
    return sendCmd(serviceName(), QLatin1String("pause"));
}
bool QtServiceController::resume()
{
    return sendCmd(serviceName(), QLatin1String("resume"));
}
bool QtServiceController::stop()
{
    return sendCmd(serviceName(), QLatin1String("terminate"));
}
Beispiel #27
0
/*!
 * Returns a list of regions the endpoint supports for \e {at least one} of the
 * the given \a {transport}s.
 *
 * Alternatvely, AwsEndpoint::regionName may be used to get this endpoint's
 * \e primary region.
 */
QStringList AwsEndpoint::supportedRegions(const Transports transport) const
{
    return supportedRegions(serviceName(), transport);
}
Beispiel #28
0
int processArgs(int argc, char **argv)
{
    if (argc > 2) {
        QString arg1(argv[1]);
        if (arg1 == QLatin1String("-i") ||
                arg1 == QLatin1String("-install")) {
            if (argc > 2) {
                QString account;
                QString password;
                QString path(argv[2]);
                if (argc > 3) {
                    account = argv[3];
                }
                if (argc > 4) {
                    password = argv[4];
                }
                printf("The service %s installed.\n",
                       (QtServiceController::install(path, account, password) ? "was" : "was not"));
                return 0;
            }
        } else {
            QString serviceName(argv[1]);
            QtServiceController controller(serviceName);
            QString option(argv[2]);
            if (option == QLatin1String("-u") ||
                    option == QLatin1String("-uninstall")) {
                printf("The service \"%s\" %s uninstalled.\n",
                       controller.serviceName().toLatin1().constData(),
                       (controller.uninstall() ? "was" : "was not"));
                return 0;
            } else if (option == QLatin1String("-s") ||
                       option == QLatin1String("-start")) {
                QStringList args;
                for (int i = 3; i < argc; ++i) {
                    args.append(QString::fromLocal8Bit(argv[i]));
                }
                printf("The service \"%s\" %s started.\n",
                       controller.serviceName().toLatin1().constData(),
                       (controller.start(args) ? "was" : "was not"));
                return 0;
            } else if (option == QLatin1String("-t") ||
                       option == QLatin1String("-terminate")) {
                printf("The service \"%s\" %s stopped.\n",
                       controller.serviceName().toLatin1().constData(),
                       (controller.stop() ? "was" : "was not"));
                return 0;
            } else if (option == QLatin1String("-p") ||
                       option == QLatin1String("-pause")) {
                printf("The service \"%s\" %s paused.\n",
                       controller.serviceName().toLatin1().constData(),
                       (controller.pause() ? "was" : "was not"));
                return 0;
            } else if (option == QLatin1String("-r") ||
                       option == QLatin1String("-resume")) {
                printf("The service \"%s\" %s resumed.\n",
                       controller.serviceName().toLatin1().constData(),
                       (controller.resume() ? "was" : "was not"));
                return 0;
            } else if (option == QLatin1String("-c") ||
                       option == QLatin1String("-command")) {
                if (argc > 3) {
                    QString codestr(argv[3]);
                    int code = codestr.toInt();
                    printf("The command %s sent to the service \"%s\".\n",
                           (controller.sendCommand(code) ? "was" : "was not"),
                           controller.serviceName().toLatin1().constData());
                    return 0;
                }
            } else if (option == QLatin1String("-v") ||
                       option == QLatin1String("-version")) {
                bool installed = controller.isInstalled();
                printf("The service\n"
                       "\t\"%s\"\n\n", controller.serviceName().toLatin1().constData());
                printf("is %s", (installed ? "installed" : "not installed"));
                printf(" and %s\n\n", (controller.isRunning() ? "running" : "not running"));
                if (installed) {
                    printf("path: %s\n", controller.serviceFilePath().toLatin1().data());
                    printf("description: %s\n", controller.serviceDescription().toLatin1().data());
                    printf("startup: %s\n", controller.startupType() == QtServiceController::AutoStartup ? "Auto" : "Manual");
                }
                return 0;
            }
        }
    }
    printf("controller [-i PATH | SERVICE_NAME [-v | -u | -s | -t | -p | -r | -c CODE] | -h] [-w]\n\n"
           "\t-i(nstall) PATH\t: Install the service\n"
           "\t-v(ersion)\t: Print status of the service\n"
           "\t-u(ninstall)\t: Uninstall the service\n"
           "\t-s(tart)\t: Start the service\n"
           "\t-t(erminate)\t: Stop the service\n"
           "\t-p(ause)\t: Pause the service\n"
           "\t-r(esume)\t: Resume the service\n"
           "\t-c(ommand) CODE\t: Send a command to the service\n"
           "\t-h(elp)\t\t: Print this help info\n"
           "\t-w(ait)\t\t: Wait for keypress when done\n");
    return 0;
}
/*!
    Executes the service.

    When the exec() function is called, it will parse the \l
    {serviceSpecificArguments} {service specific arguments} passed in
    \c argv, perform the required actions, and exit.

    If none of the arguments is recognized as service specific, exec()
    will first call the createApplication() function, then executeApplication() and
    finally the start() function. In the end, exec()
    returns while the service continues in its own process waiting for
    commands from the service controller.

    \sa QtServiceController
*/
int QtService::exec(const std::map<QString, QVariant> &args)
{

    d_ptr->args = args;
    int ec = d_ptr->run();
    if (ec == -1)
        qErrnoWarning("The service could not be executed.");
    return ec;

#if defined(Q_OS_UNIX)
    if (::getenv("QtService_RUN")) {
        // Means we're the detached, real service process.
        int ec = d_ptr->run(true, d_ptr->args);
        if (ec == -1)
            qErrnoWarning("The service failed to run.");
        return ec;
    }
#endif
    if (!d_ptr->start()) {
        fprintf(stderr, "The service %s could not start\n Run with argument -h for help.\n", serviceName().toLatin1().constData());
        return -4;
    }
    return 0;
}
Beispiel #30
0
int XHServiceBase::exec()
{
    if (d_ptr->args.size() > 1) {
        std::string a =  d_ptr->args.at(1);
        if (a == std::string("-i") || a == std::string("-install")) {
            if (!d_ptr->controller.isInstalled()) {
                std::string account;
                std::string password;
                if (d_ptr->args.size() > 2)
                    account = d_ptr->args.at(2);
                if (d_ptr->args.size() > 3)
                    password = d_ptr->args.at(3);
                if (!d_ptr->install(account, password)) {
                    fprintf(stderr, "The service [%s] could not be installed\n%s\n", 
						serviceName().c_str());
                    return -1;
                } else {
                    printf("The service [%s] has been installed under: %s\n",
                        serviceName().c_str(), d_ptr->filePath().c_str());
                }
            } else {
				fprintf(stderr, "The service [%s] is already installed\n", serviceName().c_str());
            }
            return 0;
        } else if (a == std::string("-u") || a == std::string("-uninstall")) {
            if (d_ptr->controller.isInstalled()) {
                if (!d_ptr->controller.uninstall()) {
                    fprintf(stderr, "The service [%s] could not be uninstalled\n", serviceName().c_str());
                    return -1;
                } else {
                    printf("The service [%s] has been uninstalled.\n",serviceName().c_str());
                }
            } else {
                fprintf(stderr, "The service [%s] is not installed\n", serviceName().c_str());
            }
            return 0;
        } else if (a == std::string("-v") || a == std::string("-version")) {
            printf("The service\n"
                "\t[%s]\n\t%s\n\n", serviceName().c_str(), d_ptr->args[0].c_str());
            printf("is %s", (d_ptr->controller.isInstalled() ? "installed" : "not installed"));
            printf(" and %s\n\n", (d_ptr->controller.isRunning() ? "running" : "not running"));
            return 0;
		}
		else if (a == std::string("-e") || a == std::string("-exec")) {
			std::vector<std::string>::iterator it = d_ptr->args.begin() + 1;
			d_ptr->args.erase(it);
			int ec = d_ptr->run(false, d_ptr->args);
			if (ec == -1)
				fprintf(stderr, "The service could not be executed.");
			return ec;
        } else if (a == std::string("-t") || a == std::string("-terminate")) {
            if (!d_ptr->controller.stop())
				fprintf(stderr, "The service could not be stopped.");
            return 0;
        } else if (a == std::string("-p") || a == std::string("-pause")) {
            d_ptr->controller.pause();
            return 0;
        } else if (a == std::string("-r") || a == std::string("-resume")) {
            d_ptr->controller.resume();
            return 0;
        } else if (a == std::string("-c") || a == std::string("-command")) {
            int code = 0;
			if (d_ptr->args.size() > 2){
				std::string _v = d_ptr->args[2];
				code = atoi(_v.c_str());
			}
            d_ptr->controller.sendCommand(code);
            return 0;
        } else if(a == std::string("-h") || a == std::string("-help")) {
			printHelp();
            return 0;
		}
	}
#if defined(Q_OS_UNIX)
	if (::getenv("XHSERVICE_RUN")) {
		// Means we're the detached, real service process.
		int ec = d_ptr->run(true, d_ptr->args);
		if (ec == -1)
			fprintf(stderr, "The service [%s] could not start\n", serviceName().c_str());
		return ec;
	}
#endif
	if (!d_ptr->start()) {
		fprintf(stderr, "The service [%s] could not start\n", serviceName().c_str());
		return -4;
	}
	return 0;
}