Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 47
Текст из файла (страница 47)
You do this by calling the SaveL() function ofthe application UI in the exit cases of HandleCommandL():void COandXAppUi::HandleCommandL(TInt aCommand){switch(aCommand){case EEikCmdExit:case EAknSoftkeyExit:{SaveL() ;Exit() ;}break;...}UIQ applications don’t normally exit, unless they are forced to do so bythe memory manager. If the memory manager needs to recover memory, itcalls an application document’s MSaveObserver::SaveL() function,passing it a value of MSaveObserver::EReleaseRAM. On receipt ofthis value, an application is expected to save its state and data and thenclose down; this is the default action for all applications that derive theirdocument class from CQikDocument.
Any application that ignores thisrequest – for example, by deriving its document from CEikDocument orby providing its own implementation of MSaveObserver::SaveL()– is liable to be forced to close, without any further opportunity tosave its state and data. System applications and applications that havemarked themselves as busy using CEikonEnv::SetBusy() are notforced to close.Dictionary Stores and INI FilesIn addition to an application’s document file, the application architectureprovides support for an application to open, read and modify a secondfile. By convention, the file has the same name as the application, buthas the extension .ini; hence such files are known as INI files.The intention is that an INI file should be used to store global settingsand preferences that are independent of the document data that the238FILES AND THE FILE SYSTEMapplication is processing.
An application can then, in principle, open adifferent document without affecting the existing preference settings.In practice, applications running on mobile phones tend to use onlya single document and therefore have no real need to use INI files. Inrecognition of this fact, the S60 UI disables the application architecture’ssupport for INI files, but it is a simple matter to restore it if necessary, byreplacing the OpenIniFileLC() function of CAknApplication witha call to the CEikApplication function, such as:CDictionaryStore* CMyAppApplication:: OpenIniFileLC(RFs& aFs) const{return CEikApplication::OpenIniFileLC(aFs);}As well as opening the application’s INI file for exclusive read–writeaccess – and pushing it to the cleanup stack – this function creates the INIfile if it does not exist and replaces a corrupt file.
The function is calledby the application architecture, for example to record the last openedfile, and can be called by your application code.The INI file is represented by an instance of CDictionaryFileStore, which derives from the CDictionaryStore base class. Theseclass names are slightly misleading since they have no connection withstream dictionaries. Also, since they do not derive from CStreamStore,they do not represent stream stores. Despite this, there are similaritiesof usage: the dictionary store contains streams associated with UIDs,and you read and write the streams by means of RDictionaryReadStream and RDictionaryWriteStream classes, in the same way asyou would with a stream store.However, a significant difference is that a dictionary store never contains more than a simple list of streams, unlike the complex network that ispossible in a stream store.
Furthermore, you use UIDs to access the streamsdirectly, as illustrated in Figure 7.5, rather than via a stream dictionary.UIDUIDUIDUIDUIDFigure 7.5A dictionary storeSUMMARY239The following simple examples, designed to be used as memberfunctions of an application’s application UI, illustrate writing to andreading from the application’s INI file.void WriteToIniFileL(RFs& aFs){CDictionaryStore* iniFile = Application() ->OpenIniFileLC(aFs);RDictionaryWriteStream stream;// direct access by UIDstream.AssignLC(*iniFile, TUid::Uid(0x101ffac5));TUint16 i = 0x3456;stream << i;stream.CommitL() ;iniFile->CommitL() ;CleanupStack::PopAndDestroy(2); // stream and iniFile}void ReadIniFileL(RFs& aFs){CDictionaryStore* iniFile = Application() ->OpenIniFileLC(aFs);RDictionaryReadStream readStream;// direct access by UIDreadStream.OpenLC(*iniFile, TUid::Uid(0x101ffac5));TInt16 i;readStream >> i;CleanupStack::PopAndDestroy(2); // readStream and iniFile}SummaryIn this chapter, we have discussed the following topics.• Symbian OS has a system server that provides basic file and directorymanipulation.• Several file systems and media types are typically supported by aSymbian OS phone.• The introduction of platform security dictates where an applicationshould locate files within a file system.
A private directory is usefulfor private data.• An RFile has limited functionality: basic file reads and writes; richerAPIs are required to assist application developers.• Files located in a process’s private directory can be shared withanother process by file handle. This allows a server to share its datawhile storing it in a secure location.• An RFileBuf provides additional buffering to an RFile. This isuseful for applications that load data repeatedly from a file in smallsections.240FILES AND THE FILE SYSTEM• A file stream builds on this functionality by allowing specific datastructures from a class to be externalized and internalized to and froma file.• If more than one object must be externalized, separate streams maybe desirable.
A collection of streams can be saved in a single entitycalled a store.• File-based stores are called persistent stores as they persist over adevice power cycle, provided that they are stored on non-volatilemedia.• Direct stores are written to once and then replaced in their entirety.• Permanent stores are those in which streams can be modified aftercreation. Maintenance, such as reclamation, is required to free spacepreviously used by a permanent store.• A stream can be located by a stream ID, which is stored in a dictionarystream in a known location.• A dictionary store is useful as each stream can be accessed directlyby UID instead of stream ID.• Store files can grow in complexity.
At some point, you must decidewhether to use a database.8Interprocess CommunicationMechanismsThis chapter examines the interprocess communication (IPC) mechanismsavailable to applications and servers in Symbian OS. Understandingwhen and how these are required is essential in properly architectingcomponents and making optimum use of the capabilities of the operatingsystem. Each of these mechanisms has its own strengths and limitations,so it is important to choose the right one for a particular task.Symbian OS offers thread-signaling and synchronization primitives,such as semaphores and mutexes, that can be used to manage and signalownership of shared memory between threads and processes [Sales2005], but those are quite low level and basic and are not dealt withhere. Symbian OS also offers IPC mechanisms and APIs to exchange databetween threads and processes, using higher-level abstractions such asclient–server, publish and subscribe and message queues.8.1 OverviewClient–Server Session IPCSince the whole of Symbian OS was architected around event-driven,user-initiated interactions, the communication mechanism of choice formost user-space components is the client–server session-based IPC.
Thisis the case because the focus is on providing responsiveness to humanusers, while enabling many components and applications to share servicesand resources. These services and resources, as discussed in Chapter 2,are accessed through user-side servers that mediate access to them; hencethe ubiquitous use of the client–server IPC mechanism.Starting in the early 1980s, Symbian OS and its 16-bit EPOC predecessor were designed for people to use and interact with. This is in242INTERPROCESS COMMUNICATION MECHANISMScontrast to most other embedded and real-time operating systems, whichhave been designed for use without a user interface, in data planes orcontrol systems.
From the outset, devices using Symbian OS had to copewith large amounts of user-initiated I/O, so CPU cycles were preciousand reserved for the user. In such an environment, where many applications are using many services simultaneously, all interactions have tobe asynchronous and non-blocking, thus ensuring responsiveness for theuser.In client–server IPC, clients connect to servers by name. The firsttask is to establish a session that then provides the context for allfurther communication between the client and the server.
Such sessionbased communication comprises client requests and server responses(see Figure 8.1). Within the Symbian OS kernel, which mediates allmessages, such requests and responses are associated through sessionobjects. For each session, the kernel delivers messages that the servercan use to retrieve data from the relevant client’s space (through kernelmediation), process the data and then return. Finally, the server notifiesthe client that its request is complete. Due to its connection-oriented(albeit message-centric) session-based communication, the client–servermechanism provides a guaranteed request-completion mechanism.Response dataClientIPC sessionServerResourceIPC sessionClientFigure 8.1Client–server IPC mechanismFor communication to take place in this way, a session object has tobe established in the kernel, with a guaranteed number of message slotsfor the server.
This defines the maximum number of parallel outstandingrequests which a particular client can issue to the server. Session-basedcommunication ensures that all clients are notified in the case of an erroror shutdown of a server and that all resources are cleared when a clientdisconnects or dies or something else goes wrong.This type of communication paradigm is good for when many clientsneed to reliably access a service or shared resource concurrently. In thatcase the server serializes and mediates access to the service accordingly.Clients must initiate a connection to the server and the server is there toOVERVIEW243respond on demand; thus the relationship between clients and servers isone-to-one but not peer-to-peer. For client services and user-initiated I/O,the Symbian OS client–server IPC serves its lightweight micro-kernelbased architecture well.When deciding whether or not to use client–server IPC, you need tobear the following points in mind:• clients must know which server provides the service they want• permanent sessions are maintained between clients and server• client–server IPC is not really suitable for event multicasting• although delivery is guaranteed, there is no guarantee of real-time,deterministic delivery.Publish and Subscribe IPCPublish and subscribe (P&S) is an IPC mechanism, also known as ‘properties’, that provides a means to define and publish system-wide globalvariables.