Главная » Просмотр файлов » Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007

Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887), страница 54

Файл №779887 Wiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (Symbian Books) 54 страницаWiley.Developing.Software.for.Symbian.OS.2nd.Edition.Dec.2007 (779887) страница 542018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

Текст из файла (страница 54)

Each task simply printsa message every time its RunL() runs and then restarts the timer.CPrimaryTask’s method StartRunning() begins the task. The firstargument is a count that specifies how many times RunL() is invokedbefore the EXE will exit. The second argument is the time interval (inmicroseconds) after which the task’s RunL() is invoked.

CBackgroundis similar to CPrimaryTask except you start it via a method calledStartBackground(), specifying only the task interval (it does notcontrol when the EXE exits).USING ACTIVE OBJECTS FOR BACKGROUND TASKS275When CPrimaryTask::RunL() has executed for the number oftimes specified in the StartRunning() method, it calls CActiveScheduler::Stop(). This causes the active scheduler to exit, andcontrol returns to ActiveExampleL() past the CActiveScheduler::Start() statement. In other words, CActiveScheduler::Start() returns since the event loop is finished.Here is the MMP file for the example:TARGETTARGETTYPEUIDSOURCEPATHSOURCEUSERINCLUDESYSTEMINCLUDELIBRARYactive.exeexe0 0xE00000298.active.cpp.\Epoc32\includeeuser.lib efsrv.libThis example both writes its output to the console and uses RDebugto write the output to the epocwind.out file and/or the IDE outputconsole as described in section 5.6.4.An example of the output from this example is shown below.CPrimaryTask: RunLCPrimaryTask: RunLCPrimaryTask: RunLCBackground RunLCPrimaryTask: RunLCPrimaryTask: RunLCPrimaryTask: RunLCPrimaryTask: RunLCBackground RunLCPrimaryTask: RunLCPrimaryTask: RunLCPrimaryTask: RunLCBackground RunLCPrimaryTask: RunLCPrimaryTask: RunLCPrimaryTask: RunLCPrimaryTask: RunLCBackground RunLCPrimaryTask: RunLCPrimaryTask: RunLCPrimaryTask: RunLCPrimaryTask: RunLCBackground RunLCPrimaryTask: RunLCPrimaryTask: RunLScheduler exited, cleanup9Processes, Threads,and SynchronizationIn Chapter 3, I gave an overview of the multitasking capability of SymbianOS, and introduced how processes and threads are used.

This chaptercontinues that discussion by showing you specifically how to createand manage your own processes and threads using the APIs SymbianOS provides. I’ll also describe how to synchronize, and communicatebetween threads, using shared memory regions, semaphores, mutexes,and critical sections.Understanding the material in this chapter is not absolutely necessaryfor basic Symbian OS programming, since processes and threads arehandled by the system for the most part.

However, at some point you mayfind that you need to create your own processes or threads. For example,you may want to create a server that runs as a separate process, launchedby your program when needed. Or you may want to create your ownthreads if you are porting code from an environment that relies heavily onthem. However, on Symbian OS, implementing threads in your programis generally discouraged in favor of using active objects (see section 9.2).Understanding the details of how processes and threads function andcommunicate will provide you with a deeper understanding of how thevarious frameworks, such as active objects and the client–server pattern,operate (these are covered in Chapters 8 and 10, respectively).9.1 ProcessesA Symbian OS process is an executable that has its own data space, stack,and heap.

A process is contained in a file that ends in .exe. Multipleprocesses can be active in memory at one time, including multipleinstances of the same EXE file.278PROCESSES, THREADS, AND SYNCHRONIZATIONBy default, a process contains a single execution thread – its mainthread – but additional threads can run in the process as well. A processis switched to whenever one of the threads in that process becomes active.Threads that run in the same process have access to the data spaceof that process and this makes exchanging data between these threadsstraightforward.

However, exchanging data between threads in differentprocesses is more involved. This is because a process cannot directly accessmemory that belongs to another process without causing a fatal exception.9.1.1 An Example ProcessThe following example shows an example process that displays aninformation message to the emulator screen every two seconds, for 100iterations, once it’s started:#include <e32base.h>TInt E32Main(){_LIT(KMsgTxt,"Process");for (TInt i=0;i<100;i++){User::InfoPrint(KMsgTxt);User::After(2000000);}return(0);}All processes contain the function E32Main(), which is where executionbegins. When E32Main() exits, the process terminates.Here is the MMP file that builds the process in an executable calledMyProc.exe:// EXE MMP fileTARGETMyProc.exeUID0 0xE000127FTARGETTYPEexeSOURCEPATH..\srcSOURCEMyProc.cppUSERINCLUDE.USERINCLUDE..\includeSYSTEMINCLUDE \Epoc32\includeLIBRARYeuser.lib9.1.2 Launching a ProcessThe following code loads and runs an instance of MyProc.exe:void LaunchProcessL(){_LIT(KMyExeFile,"MyProc.exe");RProcess proc;PROCESSES279/* This will launch the MyProc.exe, passing the specified command linedata to it (NULL in this case)*/User::LeaveIfError(proc.Create(KMyExeFile,KNullDesC));proc.Resume(); // start the process running//...proc.Close();}RProcess is the core API class for representing and controlling aprocess.

RProcess acts as a handle to a process (it’s an R class) andallows you not only to launch new processes, but also to open a handleto an already running process. This means you can perform operations onthat process, such as changing its priority, terminating it, and retrievinginformation (e.g., memory usage) from it.

Note though that to terminatea process other than your own, you will need the PowerMgmt capability(see section 9.1.8). You will also not be able to change the priority ofprotected system processes.The code above instantiates an RProcess object and then invokesits Create() method to load the EXE file specified as the first argumentfor the new process.1 After calling Create(), the process is created, butsuspended. To start the process you call the Resume() method, as in theexample.Note that Create() can fail (for example, if the EXE does not exist)and thus the error should be handled. In this case, the process leaves ifCreate() returns an error (using User::LeaveIfError()).When you are finished with the process handle, you call Close() –this closes the process handle only, it does not stop the actual processitself.Let’s look more closely at the Create() function, which is overloadedto provide several creation options (refer to the SDK API documentationfor details). The RProcess::Create() function used in the exampleis prototyped as follows:TInt RProcess::Create(const TDesC& aExecutableFile,const TDesC& aCommand,TOwnerType aType=EOwnerProcess)aExecutableFile contains the name of the process executable file.The aCommand parameter is a descriptor containing a command lineargument that specifies data to be passed to the process when it islaunched.

The aType parameter specifies handle ownership and has adefault value of EOwnerProcess to indicate that this RProcess handle1Note that the name of the process is specified with no path information because it isunnecessary. All binaries execute from the \sys\bin directory of the phone for securityreasons, as described in Chapter 7.280PROCESSES, THREADS, AND SYNCHRONIZATIONcan be used by any thread in the creating process. If aType is set toEOwnerThread, then only the creating thread can access the processvia this handle.9.1.3 Setting and Retrieving Process ArgumentsAs mentioned in the previous section, you can pass a command lineargument to your process via the second argument of RProcess::Create().

For example:void LaunchProcessWithArgL(){_LIT(KMyExeFile,"MyProc.exe");_LIT(KMyExeFileCmd,"arg1 arg2");RProcess proc;User::LeaveIfError(proc.Create(KMyExeFile,KMyExeFileCmd));proc.Resume(); // start the process running}This will pass the argument string "arg1 arg2" to the process created.To retrieve the entire command string argument within the process itself,you can call User::CommandLine() as the following shows:TBuf<200> cmdLine;User::CommandLine(cmdLine);Or you can use the class CCommandLineArguments to retrieve eachargument individually from the process, as the following example shows:CCommandLineArguments *args=CCommandLineArguments::NewL();for (TInt i=0;i<args->Count();i++){TPtrC argPtr(args->Arg(i));_LIT(KArg, "arg %d = %S");console->Printf(KArg,i,argPtr);}Which would print:arg 0 = c:\sys\bin\myproc.exearg 1 = arg1arg 2 = arg2Note that argument zero is always the process name.You must include bacline.h and link to library bafl.lib to usethe CCommandLineArguments class.PROCESSES281Another way to pass data to a process is by calling the RProcess::SetParameter() method.

This is good for passing handles to aprocess, although you can also pass integers and descriptors. Section 9.4shows an example of using SetParameter() to pass a handle toa process.9.1.4 Communicating with Other ProcessesYou can open an RProcess handle to some other, already running,process by calling the Open() method for RProcess. Once opened, theRProcess object acts as a handle to that process and you can then useother RProcess methods to operate on the referenced process.

You canopen the process by either its numeric process ID (of type TProcessId)or by passing its ASCII name (these are described shortly).The following code opens a handle to a process by its process ID:RProcess myProcess;myProcess.Open(procId);if (rc != KErrNone){/* open failed, handle error */}/* ... */myProcess.Close(); // close handle when finishedThe variable procId is the ID of the process you want to open. ProcessIDs are represented by the TProcessId class, which is a simple wrapperclass for an integer.To get the numeric ID of a process, use the RProcess::Id() method.For example, the line:RProcess().Id();will get the ID of the currently executing process.Again, make sure you close the RProcess handle when you arefinished, by using Close().

Характеристики

Тип файла
PDF-файл
Размер
3,36 Mb
Материал
Тип материала
Высшее учебное заведение

Список файлов книги

Свежие статьи
Популярно сейчас
А знаете ли Вы, что из года в год задания практически не меняются? Математика, преподаваемая в учебных заведениях, никак не менялась минимум 30 лет. Найдите нужный учебный материал на СтудИзбе!
Ответы на популярные вопросы
Да! Наши авторы собирают и выкладывают те работы, которые сдаются в Вашем учебном заведении ежегодно и уже проверены преподавателями.
Да! У нас любой человек может выложить любую учебную работу и зарабатывать на её продажах! Но каждый учебный материал публикуется только после тщательной проверки администрацией.
Вернём деньги! А если быть более точными, то автору даётся немного времени на исправление, а если не исправит или выйдет время, то вернём деньги в полном объёме!
Да! На равне с готовыми студенческими работами у нас продаются услуги. Цены на услуги видны сразу, то есть Вам нужно только указать параметры и сразу можно оплачивать.
Отзывы студентов
Ставлю 10/10
Все нравится, очень удобный сайт, помогает в учебе. Кроме этого, можно заработать самому, выставляя готовые учебные материалы на продажу здесь. Рейтинги и отзывы на преподавателей очень помогают сориентироваться в начале нового семестра. Спасибо за такую функцию. Ставлю максимальную оценку.
Лучшая платформа для успешной сдачи сессии
Познакомился со СтудИзбой благодаря своему другу, очень нравится интерфейс, количество доступных файлов, цена, в общем, все прекрасно. Даже сам продаю какие-то свои работы.
Студизба ван лав ❤
Очень офигенный сайт для студентов. Много полезных учебных материалов. Пользуюсь студизбой с октября 2021 года. Серьёзных нареканий нет. Хотелось бы, что бы ввели подписочную модель и сделали материалы дешевле 300 рублей в рамках подписки бесплатными.
Отличный сайт
Лично меня всё устраивает - и покупка, и продажа; и цены, и возможность предпросмотра куска файла, и обилие бесплатных файлов (в подборках по авторам, читай, ВУЗам и факультетам). Есть определённые баги, но всё решаемо, да и администраторы реагируют в течение суток.
Маленький отзыв о большом помощнике!
Студизба спасает в те моменты, когда сроки горят, а работ накопилось достаточно. Довольно удобный сайт с простой навигацией и огромным количеством материалов.
Студ. Изба как крупнейший сборник работ для студентов
Тут дофига бывает всего полезного. Печально, что бывают предметы по которым даже одного бесплатного решения нет, но это скорее вопрос к студентам. В остальном всё здорово.
Спасательный островок
Если уже не успеваешь разобраться или застрял на каком-то задание поможет тебе быстро и недорого решить твою проблему.
Всё и так отлично
Всё очень удобно. Особенно круто, что есть система бонусов и можно выводить остатки денег. Очень много качественных бесплатных файлов.
Отзыв о системе "Студизба"
Отличная платформа для распространения работ, востребованных студентами. Хорошо налаженная и качественная работа сайта, огромная база заданий и аудитория.
Отличный помощник
Отличный сайт с кучей полезных файлов, позволяющий найти много методичек / учебников / отзывов о вузах и преподователях.
Отлично помогает студентам в любой момент для решения трудных и незамедлительных задач
Хотелось бы больше конкретной информации о преподавателях. А так в принципе хороший сайт, всегда им пользуюсь и ни разу не было желания прекратить. Хороший сайт для помощи студентам, удобный и приятный интерфейс. Из недостатков можно выделить только отсутствия небольшого количества файлов.
Спасибо за шикарный сайт
Великолепный сайт на котором студент за не большие деньги может найти помощь с дз, проектами курсовыми, лабораторными, а также узнать отзывы на преподавателей и бесплатно скачать пособия.
Популярные преподаватели
Добавляйте материалы
и зарабатывайте!
Продажи идут автоматически
6451
Авторов
на СтудИзбе
305
Средний доход
с одного платного файла
Обучение Подробнее