void Wait() { RMutex syncMutex; if(syncMutex.OpenGlobal(KSyncMutext)!=KErrNone) User::Invariant(); syncMutex.Wait(); syncMutex.Signal(); syncMutex.Close(); }
TInt CPARAM_MESS_NAMEStep::Exec_SendReceive() { _LIT(KEsockSessStartMutex,"KESSMTX"); //Keep the descriptor short RMutex mutex; TInt r; // Protect the openning of the session // with a mutex to stop thread collision FOREVER { r = mutex.CreateGlobal(KEsockSessStartMutex()); if (r == KErrNone) break; if (r != KErrAlreadyExists) return r; r=mutex.OpenGlobal(KEsockSessStartMutex()); if (r == KErrNone) break; if (r != KErrNotFound) return r; } mutex.Wait(); // the exclusion ensures the session is started atomically iResult_Server=CreateSession(SOCKET_SERVER_NAME,Version()); // Because ESock is now loaded by the Comms Root Server which is generally started during // the boot this should commonly succeed; however for test code this is still a possibility // Hence here we try starting it; this is an atomic operation (and cheap if it's already started) if (iResult_Server==KErrNotFound) { r=StartC32(); if (r==KErrNone || r==KErrAlreadyExists) { iResult_Server=CreateSession(SOCKET_SERVER_NAME,Version()); } } mutex.Signal(); mutex.Close(); if (iResult_Server == KErrNone) { iSessionCreated = ETrue; const TInt test_id = dispatch_num<PARAM_MESS_VALUE>::result; iResult_SR = do_execute(Int2Type<test_id>()); } else { iSessionCreated = EFalse; return 0; } return r; }
TInt Thread3(TAny* a) { SThreadData2& d = *(SThreadData2*)a; RMutex m; RCondVar cv; TInt r = m.OpenGlobal(TPtrC(d.iMutexName), EOwnerThread); if (r!=KErrNone) return r; r = cv.OpenGlobal(TPtrC(d.iCondVarName), EOwnerThread); if (r!=KErrNone) return r; m.Wait(); while (r==KErrNone) { r = cv.Wait(m); ++d.iInnerLoops; } return r; }
TInt CCapabilityTestStep::StartServer() { TInt err = KErrNone; RMutex mutex; err = mutex.CreateGlobal(KSipServerStarterMutex); if (err != KErrNone) { err = mutex.OpenGlobal(KSipServerStarterMutex); if (err != KErrNone) { return err; } } mutex.Wait(); { // Protected with a mutex TFindServer findServer(KSipServerName); TFullName name; if (findServer.Next(name) == KErrNone) { mutex.Signal(); mutex.Close(); return KErrNone; // Server already running } RSemaphore semaphore; err = semaphore.CreateGlobal(KSipServerSemaphoreName,0); if (err == KErrNone) { err = CreateServerProcess(semaphore); semaphore.Close(); } } mutex.Signal(); mutex.Close(); return err; }
// -------------------------------------------------------------------------------- // void NSmlGrabMutexLC( RMutex& aMutex, const TDesC& aMutexName ) // -------------------------------------------------------------------------------- LOCAL_C void NSmlGrabMutexLC( RMutex& aMutex, const TDesC& aMutexName ) { while( ETrue ) { TInt ret = aMutex.CreateGlobal(aMutexName); if( ret == KErrNone ) // We created the mutex -> Issue wait() { aMutex.Wait(); break; } if( ret == KErrAlreadyExists ) // Mutex already existed -> Open it { ret = aMutex.OpenGlobal(aMutexName); if( ret == KErrNone ) // We got handle to the mutex -> Issue wait() { aMutex.Wait(); break; } } } CleanupClosePushL(aMutex); }
/** Application invoked as part of CommandLine tests @SYMPREQ 280 File Handle Support FunctionDesc Tests Environment slots . Acquires a Mutex for log file access Invokes EnvironmentSlotsReaderL() which returns an CApaCommandLine Object Verifies the values returned by the GET APIs of CApaCommandLine object with those of predefined values Writes "Pass" to the logfile if verification passes else "Fail" is written. */ void testEnvironmentSlotsL() { TPtrC appName; TPtrC docName; TApaCommand command = EApaCommandOpen; TBool testResult = PASS; //Get the Mutex to access the log file RMutex fileAccess; fileAccess.OpenGlobal(KTLogFileAccess); fileAccess.Wait(); /** Invoke EnvironmenstSlotsReaderL() function which would constuct the CApaCommandLine class object from the environment slots and return the pointer to that object */ //CApaCommandLine* cmdLine = CApaCommandLine::EnvironmentSlotsReaderL(); //Method CApaCommandLine::EnvironmentSlotsReaderL has been implemented in a different fashion CApaCommandLine* cmdLine; CApaCommandLine::GetCommandLineFromProcessEnvironment(cmdLine); CleanupStack::PushL(cmdLine); appName.Set(KTAppName); docName.Set(KTDocName); RFs fSession; fSession.Connect(); RFile logFile; TBufC<KMaxFilePath> testFilePath(KFilePath); //Open the Log file in Write Mode User::LeaveIfError(logFile.Replace(fSession,testFilePath,EFileWrite)); // Compare the values returned by GET APIs with pre defined values TESTCOND(appName,cmdLine->ExecutableName()); if(appName != cmdLine->ExecutableName()) { logFile.Write(KTFail); logFile.Write(KTApp); } TESTCOND(docName,cmdLine->DocumentName()); if(docName != cmdLine->DocumentName()) { logFile.Write(KTFail); logFile.Write(KTDoc); } TESTCOND(command,cmdLine->Command()); if(command != cmdLine->Command()) { logFile.Write(KTFail); logFile.Write(KTCommand); } if(testResult == PASS) { logFile.Write(KTPass); } //Close the file and the file session logFile.Close(); fSession.Close(); //Signal the Mutex fileAccess.Signal(); CleanupStack::PopAndDestroy(cmdLine); }
// ----------------------------------------------------------------------------- // InitServerL // Initialises the SatServer. // ----------------------------------------------------------------------------- // LOCAL_C void InitServerL() { LOG( SIMPLE, "SATSERVER: InitServerL calling" ) RMutex serverStartMutex; TInt createErr( serverStartMutex.CreateGlobal( KSatServerMtx ) ); if ( createErr ) { TInt openErr( serverStartMutex.OpenGlobal( KSatServerMtx ) ); User::LeaveIfError( openErr ); LOG( SIMPLE, "SATSERVER: Opened SATSERVERMTX" ) } LOG( SIMPLE, "SATSERVER: Asking ownership of SATSERVERMTX" ) serverStartMutex.Wait(); LOG( SIMPLE, "SATSERVER: Got ownership of SATSERVERMTX" ) // create server - if one of this name does not already exist TFindServer findSatServer( KSatServerName ); TFullName pathName; // Search for the server. if ( KErrNone != findSatServer.Next( pathName ) ) { // We don't already exist. // Start scheduler and server. CSatSScheduler* scheduler = new ( ELeave ) CSatSScheduler; __ASSERT_ALWAYS( scheduler != NULL, PanicServer( ESatSMainSchedulerError ) ); CleanupStack::PushL( scheduler ); CActiveScheduler::Install( scheduler ); // Rename the thread. User::RenameThread( KSatServerName ); // Create the server and connect to external interfaces. CSatSServer* server = CreateSatServerL(); CleanupStack::PushL( server ); // The scheduler needs access to the server instance. //lint -e{613} scheduler cannot be null, due assertion in creation. scheduler->SetServer( server ); // Call Rendezvous to improve startup time RProcess::Rendezvous( KErrNone ); LOG( SIMPLE, "SATSERVER: Releasing ownership of SATSERVERMTX, Starting.." ) serverStartMutex.Signal(); // start fielding requests from clients CActiveScheduler::Start(); // finished when the scheduler stops CleanupStack::PopAndDestroy( KInitServerPop ); // scheduler, server } else { LOG( SIMPLE, "SATSERVER: Releasing ownership of SATSERVERMTX, Already started" ) serverStartMutex.Signal(); } serverStartMutex.Close(); LOG( SIMPLE, "SATSERVER: InitServerL exiting" ) }
LOCAL_D void ThreadFirstTestL(RTest& aTest) { aTest.Next(_L("-- Running worker thread --")); RMutex mutex; TInt errMutex = mutex.OpenGlobal(KOwnCardMutex); User::LeaveIfError(errMutex); CleanupClosePushL(mutex); aTest.Printf(_L("Replacing the database \n")); CContactDatabase* db = CContactDatabase::ReplaceL(KDatabaseFileName); CleanupStack::PushL(db); // get a second database object CContactDatabase* dbAnother = CContactDatabase::OpenL(KDatabaseFileName); CleanupStack::PushL(dbAnother); SwitchToMainThread(mutex); // 1) Back to MT-a /////////////////////////////////////////////// // Main thread has now opened the database /////////////////////////////////////////////// aTest.Printf(_L("Populating the database \n")); PopulateDatabaseL(db, KTotalContacts); WaitForNotificationsL(db); aTest.Printf(_L("Set the Own card id \n")); TestSetOwnCardL(db); WaitForNotificationsL(db); aTest.Printf(_L("Checking count value \n")); TInt count = db->CountL(); TInt countAnother = dbAnother->CountL(); aTest.Printf(_L("Count: %d \n"), count ); aTest(count == KTotalContacts && countAnother == KTotalContacts, __LINE__); aTest.Printf(_L("Checking the id \n")); TContactItemId id = db->OwnCardId(); TContactItemId idCopy = dbAnother->OwnCardId(); aTest.Printf(_L("Id: %d \n"), id); aTest(id != KNullContactId && idCopy != KNullContactId, __LINE__); SwitchToMainThread(mutex); // 2) Back to MT-b /////////////////////////////////////////////// // Main thread has now checked the added values /////////////////////////////////////////////// DeleteMultipleContactsL(db); WaitForNotificationsL(db); aTest.Printf(_L("Checking deleted count value \n")); count = db->CountL(); countAnother = dbAnother->CountL(); aTest.Printf(_L("Count: %d \n"), count ); aTest(count == 0 && countAnother == 0, __LINE__); aTest.Printf(_L("Checking the deleted id \n")); id = db->OwnCardId(); idCopy = dbAnother->OwnCardId(); aTest.Printf(_L("Id: %d \n"), id); aTest(id == KNullContactId && idCopy == KNullContactId, __LINE__); SwitchToMainThread(mutex); // 3) Back to MT-c /////////////////////////////////////////////// // Main thread has now checked the deleted values /////////////////////////////////////////////// CleanupStack::PopAndDestroy(dbAnother); CleanupStack::PopAndDestroy(db); CleanupStack::PopAndDestroy(); // close mutex handle RThread::Rendezvous(KErrNone); // Finish) back to MT-d }
// --------------------------------------------------------- // TInt RSCPClient::Connect() // Creates a new session, and starts the server, if required. // // Status : Approved // --------------------------------------------------------- // EXPORT_C TInt RSCPClient::Connect() { Dprint( (_L("--> RSCPClient::Connect()") )); // Use a mutex-object so that two processes cannot start the server at the same time RMutex startMutex; TRAPD( errf, FeatureManager::InitializeLibL() ); if( errf != KErrNone ) { return errf; } if(FeatureManager::FeatureSupported(KFeatureIdSapDeviceLockEnhancements)) { isFlagEnabled = ETrue; } else { isFlagEnabled = EFalse; } FeatureManager::UnInitializeLib(); TInt mRet = startMutex.OpenGlobal( KSCPServerName ); if ( mRet == KErrNotFound ) { mRet = startMutex.CreateGlobal( KSCPServerName ); } if ( mRet != KErrNone ) { return mRet; } // Acquire the mutex startMutex.Wait(); TInt retry = KSCPConnectRetries; TInt r; for (;;) { r = CreateSession( KSCPServerName, Version(), KDefaultMessageSlots ); if ( ( r != KErrNotFound ) && ( r != KErrServerTerminated ) ) { break; } if ( --retry == 0 ) { break; } r = StartServer(); if ( ( r != KErrNone ) && ( r != KErrAlreadyExists ) ) { break; } } Dprint( (_L("<-- RSCPClient::Connect(), exiting: %d"), r )); // Release the mutex startMutex.Signal(); startMutex.Close(); return r; }
void CLogFileControl::WriteXml(const TDesC8 &aDes) /** * @param aDes - send a aDes string in xml format to a log file */ { /*--------- Maintaince Warning: ----------------------------------- ******* the fomat of below is sensible from client original format. ******* Any change should match actual string formated from client. ******* Double check the code on client side * The current assumtion of format: * First string values are seperated by sign " - " and extra pair of fields are * seperated from main log message by long unusual string "LogFieldsRequiredBeingAddedToAboveLogMessage" * The \t used to seperate field name and field value and \r\n used to seperate * each other from those pairs of field * \t\t\t\t\t\t is used to end of whole string --------------------------------------------------------------------------------*/ _LIT8(KxmlHeader,"<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\r\n<LOGFILE>"); //The order of variables: // time - aTime // Severity - aSeverity // Thread - aThread // Filename - aFilename // Linenumber - aLinenumber // Text - aText // Start of string retrive/deformating HBufC8* pBuf1 = HBufC8::New(KMaxLoggerLineLength*2); //(aDes.Length()+200); if(!pBuf1) { return; // no memory } TPtr8 aPtr(pBuf1->Des()); // used for searching TPtr8 alogbuf(pBuf1->Des()); //used for final log aPtr.Append(aDes); TPtrC8 SearchBuf; TInt aCount[8]; aCount[0]=0; TInt posI(0); // retrive log message: // Retrive common part of log message: TInt i=0; for(i=1; i<6; i++) { SearchBuf.Set(aPtr.Mid(posI)); aCount[i]=SearchBuf.Find(KSeperation8)+posI; posI=aCount[i]+3; if(aCount[i]<aCount[i-1]) { delete pBuf1; return; // wrong format string from client } } // seperating common log message and extra log fields will be easy for future maintaince. TLogField8* alogField = new TLogField8[6]; // the common part of log message for both // with and without extra log fields if(!alogField) { delete pBuf1; return; // no memory } TLogField8* extralogField=NULL; // only applied to extra log fields TInt alength=0; // a length of array of extra log fields alogField[0].iLogTag8.Copy(_L8("TIME")); alogField[1].iLogTag8.Copy(_L8("SEVERITY")); alogField[2].iLogTag8.Copy(_L8("THREAD")); alogField[3].iLogTag8.Copy(_L8("FILENAME")); alogField[4].iLogTag8.Copy(_L8("LINENUMBER")); alogField[5].iLogTag8.Copy(_L8("TEXT")); alogField[0].iLogValue8.Copy(aPtr.Mid(aCount[0],aCount[1]-aCount[0])); for(i=1; i<5; i++) { alogField[i].iLogValue8.Copy(aPtr.Mid(aCount[i]+3,aCount[i+1]-aCount[i]-3)); } SearchBuf.Set(aPtr.Mid(posI)); aCount[6]=SearchBuf.Find(_L8("LogFieldsRequiredBeingAddedToAboveLogMessage"))+posI; if(aCount[6]<posI) // no addtional fields. Find return value is KErrNotFound or >0 { alogField[5].iLogValue8.Copy(aPtr.Mid(aCount[5]+3,aDes.Length()-aCount[5]-5)); } else { alogField[5].iLogValue8.Copy(aPtr.Mid(aCount[5]+3,aCount[6]-aCount[5]-5)); posI=aCount[6]+45; //45 is from the length of long string and a tab SearchBuf.Set(aPtr.Mid(posI)); aCount[7]=SearchBuf.Find(_L8("\r\n"))+posI; TLex8 lex(aPtr.Mid(posI,aCount[7]-posI)); // get the length TInt err=lex.Val(alength); if (err) alength=0; // ignor the extra log fields. Let the log go // Retrive the extra log fields extralogField = new TLogField8[alength]; if(!extralogField) { delete pBuf1; return; // no memory } for(TInt i=0; i<alength; i++) { aCount[6]=aCount[7]+2; SearchBuf.Set(aPtr.Mid(aCount[6])); aCount[7]=SearchBuf.Find(_L8("\t"))+aCount[6]; extralogField[i].iLogTag8.Copy(aPtr.Mid(aCount[6],aCount[7]-aCount[6])); aCount[6]=aCount[7]+1; SearchBuf.Set(aPtr.Mid(aCount[6])); aCount[7]=SearchBuf.Find(_L8("\r\n"))+aCount[6]; extralogField[i].iLogValue8.Copy(aPtr.Mid(aCount[6],aCount[7]-aCount[6])); } } // Start to organize an XML format: TInt afileSize; _LIT(KLogMutex, "LoggingServerMutex"); RMutex mutex; TInt r = mutex.CreateGlobal(KLogMutex); if(r==KErrAlreadyExists) r = mutex.OpenGlobal(KLogMutex); if(!r) mutex.Wait(); // If still failed, let logging go without bother the mutex. iLogFile.Size(afileSize); if(afileSize<12) // 12 is from charters of "\r\n</LOGFILE>" //It shoud happened once at the beginning of the file // such as overwrite mode { afileSize=12; // used for lock position alogbuf.Copy(KxmlHeader); } alogbuf.Append(_L8("\r\n<MESSAGE>\r\n")); for(TInt i=0; i<6; i++) { alogbuf.Append(_L8(" <")); alogbuf.Append(alogField[i].iLogTag8); alogbuf.Append(_L8(">")); alogbuf.Append(alogField[i].iLogValue8); alogbuf.Append(_L8("</")); alogbuf.Append(alogField[i].iLogTag8); alogbuf.Append(_L8(">\r\n")); } for(TInt i=0; i<alength; i++) { alogbuf.Append(_L8(" <")); alogbuf.Append(extralogField[i].iLogTag8); alogbuf.Append(_L8(">")); alogbuf.Append(extralogField[i].iLogValue8); alogbuf.Append(_L8("</")); alogbuf.Append(extralogField[i].iLogTag8); alogbuf.Append(_L8(">\r\n")); } alogbuf.Append(_L8("</MESSAGE>")); alogbuf.Append(_L8("\r\n</LOGFILE>")); iLogFile.Write(afileSize-12, alogbuf,iStatus); if(!r) { mutex.Signal(); mutex.Close(); } if(extralogField) delete[] extralogField; delete[] alogField; delete pBuf1; }