⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 qprocess_unix.cpp

📁 qt-x11-opensource-src-4.1.4.tar.gz源码
💻 CPP
📖 第 1 页 / 共 2 页
字号:
/******************************************************************************** Copyright (C) 1992-2006 Trolltech ASA. All rights reserved.**** This file is part of the QtCore module of the Qt Toolkit.**** This file may be used under the terms of the GNU General Public** License version 2.0 as published by the Free Software Foundation** and appearing in the file LICENSE.GPL included in the packaging of** this file.  Please review the following information to ensure GNU** General Public Licensing requirements will be met:** http://www.trolltech.com/products/qt/opensource.html**** If you are unsure which license is appropriate for your use, please** review the following information:** http://www.trolltech.com/products/qt/licensing.html or contact the** sales department at sales@trolltech.com.**** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.******************************************************************************///#define QPROCESS_DEBUG#include "qdebug.h"#ifndef QT_NO_PROCESS#if defined QPROCESS_DEBUG#include "qstring.h"#include <ctype.h>/*    Returns a human readable representation of the first \a len    characters in \a data.*/static QByteArray qt_prettyDebug(const char *data, int len, int maxSize){    if (!data) return "(null)";    QByteArray out;    for (int i = 0; i < len; ++i) {        char c = data[i];        if (isprint(c)) {            out += c;        } else switch (c) {        case '\n': out += "\\n"; break;        case '\r': out += "\\r"; break;        case '\t': out += "\\t"; break;        default:            QString tmp;            tmp.sprintf("\\%o", c);            out += tmp.toLatin1();        }    }    if (len < maxSize)        out += "...";    return out;}#endif#include "qplatformdefs.h"#include "qprocess.h"#include "qprocess_p.h"#ifdef Q_OS_MAC#include <private/qcore_mac_p.h>#endif#include <qabstracteventdispatcher.h>#include <private/qcoreapplication_p.h>#include <qdatetime.h>#include <qfile.h>#include <qfileinfo.h>#include <qlist.h>#include <qmap.h>#include <qmutex.h>#include <qsemaphore.h>#include <qsocketnotifier.h>#include <qthread.h>#include <errno.h>#include <stdlib.h>static int qt_qprocess_deadChild_pipe[2];static void (*qt_sa_old_sigchld_handler)(int) = 0;static void qt_sa_sigchld_handler(int signum){    ::write(qt_qprocess_deadChild_pipe[1], "", 1);#if defined (QPROCESS_DEBUG)    fprintf(stderr, "*** SIGCHLD\n");#endif    if (qt_sa_old_sigchld_handler && qt_sa_old_sigchld_handler != SIG_IGN)        qt_sa_old_sigchld_handler(signum);}struct QProcessInfo {    QProcess *process;    int deathPipe;    int exitResult;    pid_t pid;    int serialNumber;};class QProcessManager : public QThread{    Q_OBJECTpublic:    QProcessManager();    ~QProcessManager();    void run();    void catchDeadChildren();    void add(pid_t pid, QProcess *process);    void remove(QProcess *process);    void lock();    void unlock();private:    QMutex mutex;    QMap<int, QProcessInfo *> children;};Q_GLOBAL_STATIC(QProcessManager, processManager)QProcessManager::QProcessManager(){#if defined (QPROCESS_DEBUG)    qDebug() << "QProcessManager::QProcessManager()";#endif    // initialize the dead child pipe and make it non-blocking. in the    // extremely unlikely event that the pipe fills up, we do not under any    // circumstances want to block.    ::pipe(qt_qprocess_deadChild_pipe);    ::fcntl(qt_qprocess_deadChild_pipe[0], F_SETFD, FD_CLOEXEC);    ::fcntl(qt_qprocess_deadChild_pipe[1], F_SETFD, FD_CLOEXEC);    ::fcntl(qt_qprocess_deadChild_pipe[0], F_SETFL,	    ::fcntl(qt_qprocess_deadChild_pipe[0], F_GETFL) | O_NONBLOCK);    ::fcntl(qt_qprocess_deadChild_pipe[1], F_SETFL,	    ::fcntl(qt_qprocess_deadChild_pipe[1], F_GETFL) | O_NONBLOCK);    // set up the SIGCHLD handler, which writes a single byte to the dead    // child pipe every time a child dies.    struct sigaction oldAction;    struct sigaction action;    memset(&action, 0, sizeof(action));    action.sa_handler = qt_sa_sigchld_handler;    action.sa_flags = SA_NOCLDSTOP;    ::sigaction(SIGCHLD, &action, &oldAction);    if (oldAction.sa_handler != qt_sa_sigchld_handler)	qt_sa_old_sigchld_handler = oldAction.sa_handler;}QProcessManager::~QProcessManager(){    // notify the thread that we're shutting down.    ::write(qt_qprocess_deadChild_pipe[1], "@", 1);    ::close(qt_qprocess_deadChild_pipe[1]);    wait();    // on certain unixes, closing the reading end of the pipe will cause    // select in run() to block forever, rather than return with EBADF.    ::close(qt_qprocess_deadChild_pipe[0]);    qt_qprocess_deadChild_pipe[0] = -1;    qt_qprocess_deadChild_pipe[1] = -1;    qDeleteAll(children.values());    children.clear();}void QProcessManager::run(){    forever {        fd_set readset;        FD_ZERO(&readset);        FD_SET(qt_qprocess_deadChild_pipe[0], &readset);#if defined (QPROCESS_DEBUG)        qDebug() << "QProcessManager::run() waiting for children to die";#endif        // block forever, or until activity is detected on the dead child        // pipe. the only other peers are the SIGCHLD signal handler, and the        // QProcessManager destructor.        int nselect = select(qt_qprocess_deadChild_pipe[0] + 1, &readset, 0, 0, 0);        if (nselect < 0) {            if (errno == EINTR)                continue;            break;        }        // empty only one byte from the pipe, even though several SIGCHLD        // signals may have been delivered in the meantime, to avoid race        // conditions.        char c;        if (::read(qt_qprocess_deadChild_pipe[0], &c, 1) < 0 || c == '@')            break;        // catch any and all children that we can.        catchDeadChildren();    }}void QProcessManager::catchDeadChildren(){    QMutexLocker locker(&mutex);    // try to catch all children whose pid we have registered, and whose    // deathPipe is still valid (i.e, we have not already notified it).    QMap<int, QProcessInfo *>::Iterator it = children.begin();    while (it != children.end()) {        // notify all children that they may have died. they need to run        // waitpid() in their own thread.        QProcessInfo *info = it.value();        ::write(info->deathPipe, "", 1);#if defined (QPROCESS_DEBUG)        qDebug() << "QProcessManager::run() sending death notice to" << info->process;#endif        ++it;    }}static QBasicAtomic idCounter = Q_ATOMIC_INIT(1);static int qt_qprocess_nextId(){    register int id;    for (;;) {        id = idCounter;        if (idCounter.testAndSet(id, id + 1))            break;    }    return id;}void QProcessManager::add(pid_t pid, QProcess *process){#if defined (QPROCESS_DEBUG)    qDebug() << "QProcessManager::add() adding pid" << pid << "process" << process;#endif    // insert a new info structure for this process    QProcessInfo *info = new QProcessInfo;    info->process = process;    info->deathPipe = process->d_func()->deathPipe[1];    info->exitResult = 0;    info->pid = pid;    int serial = qt_qprocess_nextId();    process->d_func()->serial = serial;    children.insert(serial, info);}void QProcessManager::remove(QProcess *process){    QMutexLocker locker(&mutex);    int serial = process->d_func()->serial;    QProcessInfo *info = children.value(serial);    if (!info)        return;#if defined (QPROCESS_DEBUG)    qDebug() << "QProcessManager::remove() removing pid" << info->pid << "process" << info->process;#endif        children.remove(serial);    delete info;}void QProcessManager::lock(){    mutex.lock();}void QProcessManager::unlock(){    mutex.unlock();}static void qt_create_pipe(int *pipe){    if (pipe[0] != -1)        ::close(pipe[0]);    if (pipe[1] != -1)        ::close(pipe[1]);#ifdef Q_OS_IRIX    if (::socketpair(AF_UNIX, SOCK_STREAM, 0, pipe) == -1) {        qWarning("QProcessPrivate::createPipe(%p) failed: %s",                 pipe, qPrintable(qt_error_string(errno)));    }#else    if (::pipe(pipe) != 0) {        qWarning("QProcessPrivate::createPipe(%p) failed: %s",                 pipe, qPrintable(qt_error_string(errno)));    }#endif}void QProcessPrivate::destroyPipe(int *pipe){    if (pipe[1] != -1) {        ::close(pipe[1]);        pipe[1] = -1;    }    if (pipe[0] != -1) {        ::close(pipe[0]);        pipe[0] = -1;    }}void QProcessPrivate::startProcess(){    Q_Q(QProcess);#if defined (QPROCESS_DEBUG)    qDebug("QProcessPrivate::startProcess()");#endif    processManager()->start();    // Initialize pipes    qt_create_pipe(childStartedPipe);    if (QAbstractEventDispatcher::instance(q->thread())) {        startupSocketNotifier = new QSocketNotifier(childStartedPipe[0],                                                    QSocketNotifier::Read, q);        QObject::connect(startupSocketNotifier, SIGNAL(activated(int)),                         q, SLOT(_q_startupNotification()));    }    qt_create_pipe(deathPipe);    ::fcntl(deathPipe[0], F_SETFD, FD_CLOEXEC);    ::fcntl(deathPipe[1], F_SETFD, FD_CLOEXEC);    if (QAbstractEventDispatcher::instance(q->thread())) {        deathNotifier = new QSocketNotifier(deathPipe[0],                                            QSocketNotifier::Read, q);        QObject::connect(deathNotifier, SIGNAL(activated(int)),                         q, SLOT(_q_processDied()));    }    qt_create_pipe(writePipe);    if (QAbstractEventDispatcher::instance(q->thread())) {        writeSocketNotifier = new QSocketNotifier(writePipe[1],                                                  QSocketNotifier::Write, q);        QObject::connect(writeSocketNotifier, SIGNAL(activated(int)),                         q, SLOT(_q_canWrite()));        writeSocketNotifier->setEnabled(false);    }    qt_create_pipe(standardReadPipe);    qt_create_pipe(errorReadPipe);    if (QAbstractEventDispatcher::instance(q->thread())) {        standardReadSocketNotifier = new QSocketNotifier(standardReadPipe[0],                                                         QSocketNotifier::Read,                                                         q);        QObject::connect(standardReadSocketNotifier, SIGNAL(activated(int)),                         q, SLOT(_q_canReadStandardOutput()));        errorReadSocketNotifier = new QSocketNotifier(errorReadPipe[0],                                                      QSocketNotifier::Read,                                                      q);        QObject::connect(errorReadSocketNotifier, SIGNAL(activated(int)),                         q, SLOT(_q_canReadStandardError()));    }    // Start the process (platform dependent)    processState = QProcess::Starting;    emit q->stateChanged(processState);    QByteArray encodedProg = QFile::encodeName(program);    processManager()->lock();    pid_t childPid = fork();    if (childPid < 0) {        // Cleanup, report error and return        processManager()->unlock();        processState = QProcess::NotRunning;        emit q->stateChanged(processState);        processError = QProcess::FailedToStart;        q->setErrorString(QT_TRANSLATE_NOOP(QProcess, "Resource error (fork failure)"));        emit q->error(processError);        cleanup();        return;    }    if (childPid == 0) {        execChild(encodedProg);        ::_exit(-1);    }    processManager()->add(childPid, q);    pid = Q_PID(childPid);    processManager()->unlock();    // parent    ::close(childStartedPipe[1]);    ::close(standardReadPipe[1]);    ::close(errorReadPipe[1]);    ::close(writePipe[0]);    childStartedPipe[1] = -1;    standardReadPipe[1] = -1;    errorReadPipe[1] = -1;    writePipe[0] = -1;    // make all pipes non-blocking    ::fcntl(deathPipe[0], F_SETFL, ::fcntl(deathPipe[0], F_GETFL) | O_NONBLOCK);    ::fcntl(standardReadPipe[0], F_SETFL, ::fcntl(standardReadPipe[0], F_GETFL) | O_NONBLOCK);    ::fcntl(errorReadPipe[0], F_SETFL, ::fcntl(errorReadPipe[0], F_GETFL) | O_NONBLOCK);    ::fcntl(writePipe[1], F_SETFL, ::fcntl(writePipe[1], F_GETFL) | O_NONBLOCK);}void QProcessPrivate::execChild(const QByteArray &programName){    QByteArray encodedProgramName = programName;    Q_Q(QProcess);    // create argument list with right number of elements, and set the    // final one to 0.    char **argv = new char *[arguments.count() + 2];    argv[arguments.count() + 1] = 0;    // allow invoking of .app bundles on the Mac.#ifdef Q_OS_MAC    QFileInfo fileInfo(encodedProgramName);    if (encodedProgramName.endsWith(".app") && fileInfo.isDir()) {        QCFType<CFURLRef> url = CFURLCreateWithFileSystemPath(0,                                                          QCFString(fileInfo.absoluteFilePath()),                                                          kCFURLPOSIXPathStyle, true);        QCFType<CFBundleRef> bundle = CFBundleCreate(0, url);        url = CFBundleCopyExecutableURL(bundle);        if (url) {            QCFString str = CFURLCopyFileSystemPath(url, kCFURLPOSIXPathStyle);            encodedProgramName += "/Contents/MacOS/" + static_cast<QString>(str).toUtf8();        }    }#endif    // add the program name    argv[0] = ::strdup(encodedProgramName.constData());    // add every argument to the list    for (int i = 0; i < arguments.count(); ++i) {        QString arg = arguments.at(i);        argv[i + 1] = ::strdup(arg.toLocal8Bit().constData());    }    // on all pipes, close the end that we don't use    ::close(standardReadPipe[0]);    ::close(errorReadPipe[0]);    ::close(writePipe[1]);    // copy the stdin socket    ::dup2(writePipe[0], fileno(stdin));    ::close(writePipe[0]);    // copy the stdout and stderr if asked to    if (processChannelMode != QProcess::ForwardedChannels) {        ::dup2(standardReadPipe[1], fileno(stdout));        ::dup2(errorReadPipe[1], fileno(stderr));        ::close(standardReadPipe[1]);        ::close(errorReadPipe[1]);        // merge stdout and stderr if asked to        if (processChannelMode == QProcess::MergedChannels)            ::dup2(fileno(stdout), fileno(stderr));    }    // make sure this fd is closed if execvp() succeeds    ::close(childStartedPipe[0]);    ::fcntl(childStartedPipe[1], F_SETFD, FD_CLOEXEC);    // enter the working directory    if (!workingDirectory.isEmpty())        ::chdir(QFile::encodeName(workingDirectory).constData());    // this is a virtual call, and it base behavior is to do nothing.    q->setupChildProcess();    // execute the process    if (environment.isEmpty()) {        ::execvp(argv[0], argv);    } else {        // if LD_LIBRARY_PATH exists in the current environment, but        // not in the environment list passed by the programmer, then        // copy it over.#if defined(Q_OS_MAC)        static const char libraryPath[] = "DYLD_LIBRARY_PATH";#else        static const char libraryPath[] = "LD_LIBRARY_PATH";#endif        QStringList matches = environment.filter(QRegExp("^" + QByteArray(libraryPath) + "="));        char *envLibraryPath = ::getenv(libraryPath);        if (matches.isEmpty() && envLibraryPath != 0) {            QString entry = libraryPath;            entry += "=";            entry += envLibraryPath;            environment << QString(libraryPath) +  "=" + QString(envLibraryPath);        }        char **envp = new char *[environment.count() + 1];        envp[environment.count()] = 0;        for (int j = 0; j < environment.count(); ++j) {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -