int SipServerBroker::run(void *pNotUsed) { OsConnectionSocket* clientSocket = NULL; while(!isShuttingDown() && mpSocket && mpSocket->isOk()) { clientSocket = mpSocket->accept(); // post a message, containing the the client socket, to the owner // @TODO - what about when we are shutting down? if(clientSocket) { OsPtrMsg ptrMsg(OsMsg::OS_EVENT, SipTcpServer::SIP_SERVER_BROKER_NOTIFY, (void*)clientSocket); mpOwnerTask->postMessage(ptrMsg); } } OsSysLog::add(FAC_SIP, PRI_DEBUG, "SipServerBroker::run '%s' terminating %s OsSocket %p status %s", mName.data(), isShuttingDown() ? "task shutdown" : "socket problem", mpSocket, mpSocket ? ( mpSocket->isOk() ? "ok" : "not ok" ) : "deleted" ); return 0; }
// Wait until the task is shut down and the run method has exited. // Most sub classes of OsTask should call this method in // the destructor before deleting any members which are // accessed by the run method. UtlBoolean OsTaskBase::waitUntilShutDown(int milliSecToWait) { // If task is already shut down, just return. if (isShutDown()) return TRUE; UtlString taskName = getName(); if (isStarted() || isUnInitialized()) { requestShutdown(); // ask the task to shut itself down yield(); // yield the CPU so the target task can terminate } // wait up to another nineteen seconds (20 total) for the task to terminate // printing out a console complaint every second if (isShuttingDown()) { int i; // wait up to a second for the task to terminate. for (i = 0; (i < 10) && isShuttingDown(); i++) delay(milliSecToWait/200); // wait 1/10 second for (i = 1; (i < 20) && isShuttingDown(); i++) { OsSysLog::add(FAC_KERNEL, PRI_WARNING, "Task: %s failed to terminate after %f seconds", taskName.data(), (milliSecToWait * i) / 20000.0); delay(milliSecToWait/20); } // if still no response from the task, assume it is unresponsive and // destroy the object if (isShuttingDown()) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Task: %s failed to terminate after %f seconds", taskName.data(), milliSecToWait / 1000.0); } } // Do not exit if not shut down while (isShuttingDown()) { OsSysLog::add(FAC_KERNEL, PRI_ERR, "Task: %s failed to terminate, waiting...", taskName.data()); delay(300000); } return(isShutDown()); }
//--------------------------------------------------------------------- void DefaultWorkQueue::_threadMain() { // default worker thread #if OGRE_THREAD_SUPPORT LogManager::getSingleton().stream() << "DefaultWorkQueue('" << getName() << "')::WorkerFunc - thread " << OGRE_THREAD_CURRENT_ID << " starting."; // Initialise the thread for RS if necessary if (mWorkerRenderSystemAccess) { Root::getSingleton().getRenderSystem()->registerThread(); notifyThreadRegistered(); } // Spin forever until we're told to shut down while (!isShuttingDown()) { waitForNextRequest(); _processNextRequest(); } LogManager::getSingleton().stream() << "DefaultWorkQueue('" << getName() << "')::WorkerFunc - thread " << OGRE_THREAD_CURRENT_ID << " stopped."; #endif }
// The entry point for the task. // This method executes a message processing loop until either // requestShutdown(), deleteForce(), or the destructor for this object // is called. int TaoListeningTask::run(void* pArg) { OsConnectionSocket* pClientSocket = NULL; TaoTransportAgent* pAgent = NULL; if(!mpListenSocket->isOk()) { printf("!! ERROR TaoListeningTask::run: invalid server socket !!\n"); } while (!isShuttingDown() && mpListenSocket->isOk()) { pClientSocket = mpListenSocket->accept(); if(pClientSocket) { pAgent = new TaoTransportAgent(pClientSocket, mpServer); UtlBoolean agentStarted = pAgent->start(); if(!agentStarted) { osPrintf("----- TaoTransportAgent failed to start"); } agentList.push(pAgent); } } osPrintf("++++ TaoListeningTask::run shutting down.\n"); ackShutdown(); // acknowledge the task shutdown request return 0; // and then exit }
// Running code of the writer task. int GatewayWriterTask::run(void* arg) { // Get the pointer to the redirector. mpRedirector = (SipRedirectorGateway*) (arg); // Loop forever. while (!isShuttingDown()) { // Wait 1 second between iterations. delay(1000); // Check whether the maps need to be written out. mpRedirector->mMapLock.acquire(); UtlBoolean must_write = mpRedirector->mMapsModified; mpRedirector->mMapLock.release(); if (must_write) { // writeMappings seizes the lock itself. mpRedirector->writeMappings(&mpRedirector->mMappingFileName, &mpRedirector->mMapUserToContacts); } } return 0; }
// The entry point for the task. // This method executes a message processing loop until either // requestShutdown(), deleteForce(), or the destructor for this object // is called. int OsServerTask::run(void* pArg) { UtlBoolean doShutdown = FALSE; OsMsg* pMsg = NULL; OsStatus res; do { res = receiveMessage((OsMsg*&) pMsg); // wait for a message if(res == OS_SUCCESS) { doShutdown = isShuttingDown(); if (!doShutdown) { // comply with shutdown if (!handleMessage(*pMsg)) // process the message OsServerTask::handleMessage(*pMsg); } if (!pMsg->getSentFromISR()) pMsg->releaseMsg(); // free the message } else { OsSysLog::add(FAC_KERNEL, PRI_ERR, "OsServerTask receiveMessage returned: %d", res); OsSysLog::flush(); //assert(res == OS_SUCCESS); } } while (!doShutdown); return 0; // and then exit }
//------------------------------------------------------------------------- bool RTPReceiverChannelAudio::handlePacket(RTPPacketPtr packet) { UseChannelResourcePtr channelResource; { AutoRecursiveLock lock(*this); if (isShuttingDown() || isShutdown()) return false; channelResource = mChannelResource; bool shouldQueue = false; if (!channelResource) shouldQueue = true; if (mQueuedRTP.size() > 0) shouldQueue = true; if (shouldQueue) { mQueuedRTP.push(packet); if (1 == mQueuedRTP.size()) IWakeDelegateProxy::create(mThisWeak.lock())->onWake(); return true; } } if (!channelResource) return true; return channelResource->handlePacket(*packet); }
int SipRegistrar::run(void* pArg) { UtlBoolean bFatalError = false; int taskResult = 0; if (!bFatalError) { /* * If replication is configured, * the following blocks until the state of each peer is known */ startupPhase(); if (!isShuttingDown()) { // Exit if the operational phase fails (e.g. SipUserAgent reports // problems) if (operationalPhase()) { // from here on, everything happens in handleMessage taskResult = OsServerTask::run(pArg); } } } else { Os::Logger::instance().log(FAC_SIP, PRI_EMERG, "Unable to startup Rpc server (port in use?)\n"); } return taskResult; }
// Do the real work associated with terminating a Linux task void OsTaskLinux::doLinuxTerminateTask(UtlBoolean doForce) { OsStatus res; pthread_t savedTaskId; OsSysLog::add(FAC_KERNEL, PRI_DEBUG, "OsTaskLinux::doLinuxTerminateTask, deleting task thread: %x," " force = %d", (int)mTaskId, doForce); // if there is no low-level task, or entry in the name database, just return if ((mState != UNINITIALIZED) && ((int)mTaskId != 0)) { // DEBUGGING HACK: Suspend requestor if target is suspended $$$ while (isSuspended()) { suspend(); } if (!doForce) { // We are being well behaved and will wait until the task is no longer // safe from deletes. A task is made safe from deletes by acquiring // a read lock on its mDeleteGuard. In order to delete a task, the // application must acquire a write lock. This will only happen after // all of the read lock holders have released their locks. res = mDeleteGuard.acquireWrite(); assert(res == OS_SUCCESS); } savedTaskId = mTaskId; // taskUnregister sets mTaskId to zero; taskUnregister(); // Send the thread the actual cancellation request. if (mState == STARTED) { requestShutdown(); /* maybe replace this with a call to waitUntilShutDown() ? */ for(int i = 0; i < 10 && isShuttingDown(); i++) { delay(100); } } if (mState == SHUTTING_DOWN) { if (savedTaskId != 0) { pthread_cancel(savedTaskId); } } if (!doForce) { res = mDeleteGuard.releaseWrite(); // release the write lock assert(res == OS_SUCCESS); } } mState = UNINITIALIZED; }
// Destructor SipClient::~SipClient() { Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "SipClient[%s]::~ called", mName.data()); // Tell the associated thread to shut itself down. requestShutdown(); // Do not delete the event listers, as they are not subordinate. // Free the socket if(mClientSocket) { // Close the socket to unblock the run method // in case it is blocked in a waitForReadyToRead or // a read on the mClientSocket. This should also // cause the run method to exit. if (!mbSharedSocket) { Os::Logger::instance().log(FAC_SIP, PRI_DEBUG, "SipClient[%s]::~ %p socket %p closing %s socket", mName.data(), this, mClientSocket, OsSocket::ipProtocolString(mSocketType)); mClientSocket->close(); } // Wait for the task to exit so that it does not // reference the socket or other members after they // get deleted. if(isStarted() || isShuttingDown()) { waitUntilShutDown(); } if (!mbSharedSocket) { delete mClientSocket; } mClientSocket = NULL; } else if(isStarted() || isShuttingDown()) { // It should not get here but just in case waitUntilShutDown(); } }
void atexitCallback() { if (ok() && !isShuttingDown()) { ROSCPP_LOG_DEBUG("shutting down due to exit() or end of main() without cleanup of all NodeHandles"); shutdown(); } }
// Acknowledge a shutdown request // The platform specific entry point which calls the run // method should call this method immediately after run exits. // to indicate that it is now shut down. void OsTaskBase::ackShutdown(void) { OsLock lock(mDataGuard); assert(isStarted() || isShuttingDown() || isShutDown()); mState = SHUT_DOWN; }
int TaoTransportAgent::run(void* runArg) { UtlString remoteHostName; UtlString viaProtocol; UtlString fromIpAddress; while (mpSocket && mpSocket->isOk() && !isShuttingDown()) { char buffer[DEF_TAO_MAX_SOCKET_SIZE]; unsigned long bytesRead; unsigned long cookie ; unsigned long length ; memset(buffer, 0, (DEF_TAO_MAX_SOCKET_SIZE * sizeof(char))); // Look for our next message, it should start with a '1234ABCD' marker bytesRead = mpSocket->read((char*) &cookie, sizeof(unsigned long)) ; while ((bytesRead > 0) && (cookie != 0x1234ABCD)) { osPrintf("<<**>> Invalid data read from socket, trying to resynchronize...\n") ; bytesRead = readUntilDone(mpSocket, (char*) &cookie, sizeof(unsigned long)) ; } // Okay, now read length if (bytesRead > 0) { bytesRead = readUntilDone(mpSocket, (char*) &length, sizeof(unsigned long)) ; } // Finally read data if (bytesRead > 0) { bytesRead = readUntilDone(mpSocket, buffer, length) ; if (bytesRead != length) { osPrintf("<<**>> TaoTransportAgent READ MISMATCH %lu != %lu\n", bytesRead, length) ; bytesRead = 0 ; } } if(bytesRead > 0) { TaoMessage msg = TaoMessage(UtlString(buffer)); msg.setSocket((TaoObjHandle)this); //stores pointer to this class mpServer->postMessage(msg); } else if(bytesRead <= 0 || !mpSocket->isOk()) { // The socket has gone sour close down the client mpSocket->getRemoteHostName(&remoteHostName); osPrintf("Shutting down TaoTransportAgent: %s due to failed socket\n", remoteHostName.data()); break; } } #ifdef TEST_PRINT osPrintf("TaoTransportAgent: %s/%s exiting\r\n", remoteHostName.data(), viaName.data()); #endif return(0); }
// Request a task shutdown. // The run() method of the derived class is expected to call the // isShuttingDown() method to detect when a task shutdown has been // requested. void OsTaskBase::requestShutdown(void) { OsLock lock(mDataGuard); if (!isStarted() && !isShuttingDown()) mState = SHUT_DOWN; else mState = SHUTTING_DOWN; }
int SipTlsServer::run(void* runArgument) { while (!isShuttingDown()) { OsTask::delay(500); // this method really shouldn't do anything } return(0); }
int run(void* pArg) { OsStatus status; while(!isShuttingDown()) { if (mDelay > 0) { delay(mDelay); } status = mpNotification->signal(0); } return 0; }
int NatTraversalRules::StunClient::run( void* runArg ) { UtlString discoveredPublicIpAddress; OsStatus rc; while( !isShuttingDown() ) { rc = mTimerMutex.acquire( mpNatTraversalRulesToKeepCurrent->getStunRefreshIntervalInSecs() * 1000 ); if( rc == OS_WAIT_TIMEOUT ) { if( getPublicIpAddress( discoveredPublicIpAddress ) == true ) { if( discoveredPublicIpAddress.compareTo( mPublicIpAddressObtainedFromLastPoll ) != 0 ) { mPublicIpAddressObtainedFromLastPoll = discoveredPublicIpAddress; mpNatTraversalRulesToKeepCurrent->announceStunResolvedPublicIpAddress( discoveredPublicIpAddress ); } } } } return 0; }
// Gets the decoding status. UtlBoolean StreamWAVFormatDecoder::isDecoding() { return (isStarted() || isShuttingDown()); }
// The entry point for the task. // This method executes a message processing loop until either // requestShutdown(), deleteForce(), or the destructor for this object // is called. int OsTimerTask::run(void* pArg) { UtlBoolean doShutdown; OsMsg* pMsg = NULL; OsStatus res; // "now" is the current time. OsTimer::Time now = OsTimer::now(); doShutdown = FALSE; do { // Do not attempt to receive message if a timer has already fired. // (This also avoids an edge case if the timeout value is zero // or negative.) if (!(mTimerQueue && OsTimer::compareTimes(now, mTimerQueue->mQueuedExpiresAt) >= 0)) { // Set the timeout till the next timer fires. OsTime timeout; if (mTimerQueue) { OsTimer::cvtToOsTime(timeout, OsTimer::subtractTimes(mTimerQueue->mQueuedExpiresAt, now)); } else { timeout = OsTime::OS_INFINITY; } res = receiveMessage((OsMsg*&) pMsg, timeout); // wait for a message if (res == OS_SUCCESS) { // A message was received. Process it. doShutdown = isShuttingDown(); if (!doShutdown) { // comply with shutdown if (!handleMessage(*pMsg)) // process the message { OsServerTask::handleMessage(*pMsg); } } if (!pMsg->getSentFromISR()) { pMsg->releaseMsg(); // free the message } } else { assert(pMsg==NULL); } now = OsTimer::now(); // Update our record of the current time. } // Now check for timers that have expired. while (mTimerQueue && OsTimer::compareTimes(now, mTimerQueue->mQueuedExpiresAt) >= 0) { // Fire the the timer (and remove it from the queue). OsTimer* timer = mTimerQueue; mTimerQueue = timer->mTimerQueueLink; // Clear the timer's mTimerQueueLink to indicate it is not // in the timer queue. timer->mTimerQueueLink = 0; fireTimer(timer); } if (OsSysLog::willLog(FAC_KERNEL, PRI_WARNING)) { // Check to see if timer firing took too long. OsTimer::Time after = OsTimer::now(); OsTimer::Time t = OsTimer::subtractTimes(after, now); if (t >= 1000000 /* 1 second */) { OsSysLog::add(FAC_KERNEL, PRI_WARNING, "OsTimerTask::run firing took %"PRId64" usecs," " queue length = %d, before fire = %"PRId64", after fire = %"PRId64, t, getMessageQueue()->numMsgs(), now, after); } } } while (!doShutdown); OsSysLog::add(FAC_KERNEL, PRI_INFO, "OsTimerTask::run OsTimerTask shutting down"); return 0; // and then exit }
int HttpServer::run(void* runArg) { OsConnectionSocket* requestSocket = NULL; if (!mpServerSocket->isOk()) { OsSysLog::add( FAC_SIP, PRI_ERR, "HttpServer: port not ok" ); httpStatus = OS_PORT_IN_USE; } while(!isShuttingDown() && mpServerSocket->isOk()) { requestSocket = mpServerSocket->accept(); if(requestSocket) { if (mbPersistentConnection) { // Take this opportunity to check for any old HttpConnections that can be deleted int items = mpHttpConnectionList->entries(); if (items != 0) { int deleted = 0; UtlSListIterator iterator(*mpHttpConnectionList); HttpConnection* connection; while ((connection = dynamic_cast<HttpConnection*>(iterator()))) { if (connection->toBeDeleted()) { OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer: destroying connection %p", connection); mpHttpConnectionList->destroy(connection); ++deleted; if (mHttpConnections > 0) { --mHttpConnections; } } } items = mpHttpConnectionList->entries(); OsSysLog::add(FAC_SIP, PRI_DEBUG, "HttpServer: " "destroyed %d inactive HttpConnections, %d remaining", deleted, items); } // Create new persistent connection if (mHttpConnections < MAX_PERSISTENT_HTTP_CONNECTIONS) { ++mHttpConnections; HttpConnection* newConnection = new HttpConnection(requestSocket, this); mpHttpConnectionList->append(newConnection); OsSysLog::add(FAC_SIP, PRI_INFO, "HttpServer::run starting persistent connection %d (%p)", mHttpConnections, newConnection); newConnection->start(); } else { OsSysLog::add(FAC_SIP, PRI_ERR, "HttpServer::run exceeded persistent connection limit (%d):" " sending 503", MAX_PERSISTENT_HTTP_CONNECTIONS); HttpMessage request; HttpMessage response; // Read the http request from the socket request.read(requestSocket); // Send out-of-resources message response.setResponseFirstHeaderLine(HTTP_PROTOCOL_VERSION, HTTP_OUT_OF_RESOURCES_CODE, HTTP_OUT_OF_RESOURCES_TEXT); response.write(requestSocket); requestSocket->close(); delete requestSocket; requestSocket = NULL; } } else { HttpMessage request; // Read a http request from the socket request.read(requestSocket); UtlString remoteIp; requestSocket->getRemoteHostIp(&remoteIp); HttpMessage* response = NULL; // If request from Valid IP Address if( processRequestIpAddr(remoteIp, request, response)) { // If the request is authorized processRequest(request, response, requestSocket); } if(response) { response->write(requestSocket); delete response; response = NULL; } requestSocket->close(); delete requestSocket; requestSocket = NULL; } } else { httpStatus = OS_PORT_IN_USE; } } // while (!isShuttingDown && mpServerSocket->isOk()) if ( !isShuttingDown() ) { OsSysLog::add( FAC_SIP, PRI_ERR, "HttpServer: exit due to port failure" ); } httpStatus = OS_TASK_NOT_STARTED; return(TRUE); }
UtlBoolean TaoTransportAgent::isOk() { return(mpSocket->isOk() && !isShuttingDown()); }