コード例 #1
0
ファイル: Process.cpp プロジェクト: farva/rct
void Process::finish(int returnCode)
{
    {
        std::lock_guard<std::mutex> lock(mMutex);
        mReturn = returnCode;

        mStdInBuffer.clear();
        closeStdIn(CloseForce);
        mWantStdInClosed = false;

        if (mMode == Async) {
            // try to read all remaining data on stdout and stderr
            handleOutput(mStdOut[0], mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
            handleOutput(mStdErr[0], mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);

            closeStdOut();
            closeStdErr();
        } else {
            int w;
            char q = 'q';
            eintrwrap(w, ::write(mSync[1], &q, 1));
            eintrwrap(w, ::close(mSync[1]));
            mSync[1] = -1;
        }
    }

    if (mMode == Async)
        mFinished(this);
}
コード例 #2
0
void Process::event(const Event* event)
{
    if (event->type() == ProcessFinishedEvent::Type) {
        const ProcessFinishedEvent* pevent = static_cast<const ProcessFinishedEvent*>(event);
        if (mPid == -1) {
            error() << "process already finished, pid " << pevent->pid;
            return;
        }
        assert(mPid == pevent->pid);
        mPid = -1;
        mReturn = pevent->returnCode;

        mStdInBuffer.clear();
        closeStdIn();

        // try to read all remaining data on stdout and stderr
        handleOutput(mStdOut[0], mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
        handleOutput(mStdErr[0], mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);

        closeStdOut();
        closeStdErr();

        mFinished();
    } else {
        EventReceiver::event(event);
    }
}
コード例 #3
0
ファイル: Process.cpp プロジェクト: farva/rct
void Process::processCallback(int fd, int mode)
{
    if (mode == EventLoop::SocketError) {
        // we're closed, shut down
        return;
    }
    if (fd == mStdIn[1])
        handleInput(fd);
    else if (fd == mStdOut[0])
        handleOutput(fd, mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
    else if (fd == mStdErr[0])
        handleOutput(fd, mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);
}
コード例 #4
0
void BankSelector::handle() {
	handleBankChange();
	getBank()->handle();
	if (_controller != 0) {
		handleOutput();
	}
}
コード例 #5
0
ファイル: core.c プロジェクト: cipibad/flvParser
void handleFlvParserGetRequest(struct mg_connection *conn, const struct mg_request_info *request_info)
{

    int i;
    char content[2048];
    int content_length;
    htmlDocPtr doc;
    xmlXPathContextPtr xpathCtx;
    xmlXPathObjectPtr xpathObj;
    xpathObj = handleInput(&doc, &xpathCtx, request_info);
    if (xpathObj) {
        content_length = handleOutput(request_info, xpathObj->nodesetval, content);
        /* Cleanup */
        xmlXPathFreeObject(xpathObj);
        xmlXPathFreeContext(xpathCtx);
        xmlFreeDoc(doc); 

        mg_printf(conn,
                  "HTTP/1.1 200 OK\r\n"
                  "Content-Type: text/plain\r\n"
                  "Content-Length: %d\r\n"        // Always set Content-Length
                  "\r\n"
                  "%s",
                  content_length, content);
        
    }
}
コード例 #6
0
int		SelectPolicy::waitForEvent(int timeout)
{
	struct timeval time;
	int ret;
	fd_set *set[3];
	Clock	clock;

	while (_wait)
	{
		int t = this->handleTimers(timeout);
		if (t >= 0)
		{
			time.tv_sec = t / 1000;
			time.tv_usec = (t % 1000) * 1000;
		}
		fd_set rs = _read_set, ws = _write_set, es = _except_set;
		set[0] = (_rsize == 0) ? nullptr : &rs;
		set[1] = (_wsize == 0) ? nullptr : &ws;
		set[2] = (_esize == 0) ? nullptr : &es;
#if defined (_WIN32)
		if (!set[0] && !set[1] && !set[2])
		{
			Net::Clock::sleep(t);
			continue ;
		}
		else
#endif
			ret = ::select(_maxfd + 1, set[0], set[1], set[2], (t < 0) ? nullptr : &time);
		if ((ret == -1 && errno == EINTR) || (ret == 0 && timeout != 0))
			continue ;
		if (ret == -1)
			std::cerr << Net::getLastError() << std::endl;
		if (ret == -1  || (ret == 0 && timeout == 0))
			return ret;
		if (timeout > 0)
		{
			timeout -= clock.getElapsedTime();
			clock.update();
			if (timeout < 0)
				timeout = 0;
		}
		for (auto it = _sockets.begin(); it != _sockets.end();)
		{
			auto socket = it->first;
			auto handler = socket->getEventHandler();
			auto handle = socket->getHandle();
			++it;
			if (FD_ISSET(handle, &es))
				handler->handleClose(*socket);
			else
			{
				if (FD_ISSET(handle, &rs) && handler->handleInput(*socket) <= 0)
						handler->handleClose(*socket);
				else if (FD_ISSET(handle, &ws) && handler->handleOutput(*socket) <= 0)
						handler->handleClose(*socket);
			}
		}
	}
	return 0;
}
コード例 #7
0
ファイル: LocalProcess.cpp プロジェクト: CUEBoxer/OpenStudio
 void LocalProcess::processReadyReadStandardOutput()
 {
   directoryChanged(openstudio::toQString(m_outdir));
   if (!stopped())
   {
     handleOutput(m_process.readAllStandardOutput(), false);
   }
 }
コード例 #8
0
ファイル: LocalProcess.cpp プロジェクト: CUEBoxer/OpenStudio
  void LocalProcess::processFinished(int t_exitCode, QProcess::ExitStatus t_exitStatus)
  {
    m_fileCheckTimer.stop();

    directoryChanged(openstudio::toQString(m_outdir));
    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Finishing));

    if (!stopped())
    {
      handleOutput(m_process.readAllStandardOutput(), false);
      handleOutput(m_process.readAllStandardError(), true);
    }

    QCoreApplication::processEvents();
    directoryChanged(openstudio::toQString(m_outdir));

    emit finished(t_exitCode, t_exitStatus);
    emitStatusChanged(AdvancedStatus(AdvancedStatusEnum::Idle));
  }
コード例 #9
0
void ClassifierConfiguration::entryPoint(){

    //_begin = time(0);
    if(!fileExists(outputFilename)){
        buildClassifier();
    }else{
        logln("Output already exists: " + outputFilename);
    }
    //_end = time(0);

    ClassifierOutput *clOut = handleOutput();

    writeToCSV(clOut);


    return terminateThread();
}
コード例 #10
0
ファイル: door.cpp プロジェクト: evanelias/tournament-trivia
// Reads text from the output mailslot.
bool getOutput()
{
   DWORD nNextMessageSize, nMessagesLeft, nBytesRead;      
   bool bMessagesFound = false;
   char szBuffer[245];
   OutputData odMessage;

   // Loop as long as there's output
   do
      {
      // If unable to check the mailslot, abort door
      if ( !GetMailslotInfo(hOutputSlot, NULL, &nNextMessageSize, &nMessagesLeft, NULL) ) 
         exitDoor(2);

      // If messages left, read them
      if ( nMessagesLeft > 0 && nNextMessageSize != MAILSLOT_NO_MESSAGE )
         {
         // Ignore invalid message sizes (see MS Knowledge Base Q192276)
         // In this case, simply wait for getOutput() to be called again next timeslice.
         if ( nNextMessageSize < 0 || nNextMessageSize > 500 )
            return bMessagesFound;

         if ( !ReadFile(hOutputSlot, szBuffer, nNextMessageSize, &nBytesRead, NULL) )
            {
            local("error reading from slot");
            return bMessagesFound;
            }
         
         // Convert the text into an OutputData object
         odMessage = szBuffer;
            
         // Handle the output message
         handleOutput(odMessage);
         bMessagesFound = true;
         nPending = 0;
         }
      }
   while ( nNextMessageSize != MAILSLOT_NO_MESSAGE );

   return bMessagesFound;
}
コード例 #11
0
ファイル: Client.cpp プロジェクト: tidyoux/easy-talk
void Client::run()
{
	while(true)
	{
		if (mIsConnected)
		{
			handleInput();
			handleOutput();

			//usleep(3);
			usleep(1500000);
		}
		else
		{
			mIsConnected = tryConnect();

			usleep(1500000);
		}
	}

	uninit();
}
コード例 #12
0
ファイル: Process.cpp プロジェクト: farva/rct
Process::ExecState Process::startInternal(const Path &command, const List<String> &a, const List<String> &environ,
                                          int timeout, unsigned execFlags)
{
    mErrorString.clear();

    Path cmd = findCommand(command);
    if (cmd.isEmpty()) {
        mErrorString = "Command not found";
        return Error;
    }
    List<String> arguments = a;
    int err;

    int closePipe[2];
    eintrwrap(err, ::pipe(closePipe));
#ifdef HAVE_CLOEXEC
    if (!SocketClient::setFlags(closePipe[1], FD_CLOEXEC, F_GETFD, F_SETFD)) {
        mErrorString = "Unable to set FD_CLOEXEC";
        eintrwrap(err, ::close(closePipe[0]));
        eintrwrap(err, ::close(closePipe[1]));
        return Error;
    }
#else
#warning No CLOEXEC, Process might have problematic behavior
#endif

    eintrwrap(err, ::pipe(mStdIn));
    eintrwrap(err, ::pipe(mStdOut));
    eintrwrap(err, ::pipe(mStdErr));
    if (mMode == Sync)
        eintrwrap(err, ::pipe(mSync));

    const char **args = new const char*[arguments.size() + 2];
    // const char* args[arguments.size() + 2];
    args[arguments.size() + 1] = 0;
    args[0] = cmd.nullTerminated();
    int pos = 1;
    for (List<String>::const_iterator it = arguments.begin(); it != arguments.end(); ++it) {
        args[pos] = it->nullTerminated();
        //printf("arg: '%s'\n", args[pos]);
        ++pos;
    }

    const bool hasEnviron = !environ.empty();

    const char **env = new const char*[environ.size() + 1];
    env[environ.size()] = 0;

    if (hasEnviron) {
        pos = 0;
        //printf("fork, about to exec '%s'\n", cmd.nullTerminated());
        for (List<String>::const_iterator it = environ.begin(); it != environ.end(); ++it) {
            env[pos] = it->nullTerminated();
            //printf("env: '%s'\n", env[pos]);
            ++pos;
        }
    }

    mPid = ::fork();
    if (mPid == -1) {
        //printf("fork, something horrible has happened %d\n", errno);
        // bail out
        eintrwrap(err, ::close(mStdIn[1]));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::close(mStdOut[0]));
        eintrwrap(err, ::close(mStdErr[1]));
        eintrwrap(err, ::close(mStdErr[0]));
        eintrwrap(err, ::close(closePipe[1]));
        eintrwrap(err, ::close(closePipe[0]));
        mErrorString = "Fork failed";
        delete[] env;
        delete[] args;
        return Error;
    } else if (mPid == 0) {
        //printf("fork, in child\n");
        // child, should do some error checking here really
        eintrwrap(err, ::close(closePipe[0]));
        eintrwrap(err, ::close(mStdIn[1]));
        eintrwrap(err, ::close(mStdOut[0]));
        eintrwrap(err, ::close(mStdErr[0]));

        eintrwrap(err, ::close(STDIN_FILENO));
        eintrwrap(err, ::close(STDOUT_FILENO));
        eintrwrap(err, ::close(STDERR_FILENO));

        eintrwrap(err, ::dup2(mStdIn[0], STDIN_FILENO));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::dup2(mStdOut[1], STDOUT_FILENO));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::dup2(mStdErr[1], STDERR_FILENO));
        eintrwrap(err, ::close(mStdErr[1]));

        int ret;
        if (!mChRoot.isEmpty() && ::chroot(mChRoot.constData())) {
            goto error;
        }
        if (!mCwd.isEmpty() && ::chdir(mCwd.constData())) {
            goto error;
        }
        if (hasEnviron) {
            ret = ::execve(cmd.nullTerminated(), const_cast<char* const*>(args), const_cast<char* const*>(env));
        } else {
            ret = ::execv(cmd.nullTerminated(), const_cast<char* const*>(args));
        }
        // notify the parent process
  error:
        const char c = 'c';
        eintrwrap(err, ::write(closePipe[1], &c, 1));
        eintrwrap(err, ::close(closePipe[1]));
        ::_exit(1);
        (void)ret;
        //printf("fork, exec seemingly failed %d, %d %s\n", ret, errno, strerror(errno));
    } else {
        delete[] env;
        delete[] args;

        // parent
        eintrwrap(err, ::close(closePipe[1]));
        eintrwrap(err, ::close(mStdIn[0]));
        eintrwrap(err, ::close(mStdOut[1]));
        eintrwrap(err, ::close(mStdErr[1]));

        //printf("fork, in parent\n");

        int flags;
        eintrwrap(flags, fcntl(mStdIn[1], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdIn[1], F_SETFL, flags | O_NONBLOCK));
        eintrwrap(flags, fcntl(mStdOut[0], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdOut[0], F_SETFL, flags | O_NONBLOCK));
        eintrwrap(flags, fcntl(mStdErr[0], F_GETFL, 0));
        eintrwrap(flags, fcntl(mStdErr[0], F_SETFL, flags | O_NONBLOCK));

        // block until exec is called in the child or until exec fails
        {
            char c;
            eintrwrap(err, ::read(closePipe[0], &c, 1));
            (void)c;

            if (err == -1) {
                // bad
                eintrwrap(err, ::close(closePipe[0]));
                mErrorString = "Failed to read from closePipe during process start";
                mPid = -1;
                return Error;
            } else if (err == 0) {
                // process has started successfully
                eintrwrap(err, ::close(closePipe[0]));
            } else if (err == 1) {
                // process start failed
                eintrwrap(err, ::close(closePipe[0]));
                mErrorString = "Process failed to start";
                mPid = -1;
                return Error;
            }
        }

        ProcessThread::addPid(mPid, this, (mMode == Async));

        //printf("fork, about to add fds: stdin=%d, stdout=%d, stderr=%d\n", mStdIn[1], mStdOut[0], mStdErr[0]);
        if (mMode == Async) {
            if (EventLoop::SharedPtr loop = EventLoop::eventLoop()) {
                loop->registerSocket(mStdOut[0], EventLoop::SocketRead, std::bind(&Process::processCallback, this, std::placeholders::_1, std::placeholders::_2));
                loop->registerSocket(mStdErr[0], EventLoop::SocketRead, std::bind(&Process::processCallback, this, std::placeholders::_1, std::placeholders::_2));
            }
        } else {
            // select and stuff
            timeval started, now, *selecttime = 0;
            if (timeout > 0) {
                Rct::gettime(&started);
                now = started;
                selecttime = &now;
                Rct::timevalAdd(selecttime, timeout);
            }
            if (!(execFlags & NoCloseStdIn)) {
                closeStdIn(CloseForce);
                mWantStdInClosed = false;
            }
            for (;;) {
                // set up all the select crap
                fd_set rfds, wfds;
                FD_ZERO(&rfds);
                FD_ZERO(&wfds);
                int max = 0;
                FD_SET(mStdOut[0], &rfds);
                max = std::max(max, mStdOut[0]);
                FD_SET(mStdErr[0], &rfds);
                max = std::max(max, mStdErr[0]);
                FD_SET(mSync[0], &rfds);
                max = std::max(max, mSync[0]);
                if (mStdIn[1] != -1) {
                    FD_SET(mStdIn[1], &wfds);
                    max = std::max(max, mStdIn[1]);
                }
                int ret;
                eintrwrap(ret, ::select(max + 1, &rfds, &wfds, 0, selecttime));
                if (ret == -1) { // ow
                    mErrorString = "Sync select failed: ";
                    mErrorString += strerror(errno);
                    return Error;
                }
                // check fds and stuff
                if (FD_ISSET(mStdOut[0], &rfds))
                    handleOutput(mStdOut[0], mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
                if (FD_ISSET(mStdErr[0], &rfds))
                    handleOutput(mStdErr[0], mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);
                if (mStdIn[1] != -1 && FD_ISSET(mStdIn[1], &wfds))
                    handleInput(mStdIn[1]);
                if (FD_ISSET(mSync[0], &rfds)) {
                    // we're done
                    {
                        std::lock_guard<std::mutex> lock(mMutex);
                        assert(mSync[1] == -1);

                        // try to read all remaining data on stdout and stderr
                        handleOutput(mStdOut[0], mStdOutBuffer, mStdOutIndex, mReadyReadStdOut);
                        handleOutput(mStdErr[0], mStdErrBuffer, mStdErrIndex, mReadyReadStdErr);

                        closeStdOut();
                        closeStdErr();

                        int w;
                        eintrwrap(w, ::close(mSync[0]));
                        mSync[0] = -1;
                    }
                    mFinished(this);
                    return Done;
                }
                if (timeout) {
                    assert(selecttime);
                    Rct::gettime(selecttime);
                    const int lasted = Rct::timevalDiff(selecttime, &started);
                    if (lasted >= timeout) {
                        // timeout, we're done
                        kill(); // attempt to kill
                        mErrorString = "Timed out";
                        return TimedOut;
                    }
                    *selecttime = started;
                    Rct::timevalAdd(selecttime, timeout);
                }
            }
        }
    }
    return Done;
}