Главная » Просмотр файлов » Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007

Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890), страница 50

Файл №779890 Wiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (Symbian Books) 50 страницаWiley.Symbian.OS.C.plus.plus.for.Mobile.Phones.Aug.2007 (779890) страница 502018-01-10СтудИзба
Просмтор этого файла доступен только зарегистрированным пользователям. Но у нас супер быстрая регистрация: достаточно только электронной почты!

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

For example, the code of theRFile::Open() method looks like:TInt RFile::Open(RFs& aFs,const TDesC& aName,TUint aFileMode){return (CreateSubSession(aFs, EFsFileOpen, TIpcArgs(&aName, aMode)));}8.3 Publish and Subscribe IPCPublish and subscribe is a mechanism by which a process can define anitem of data (known as a property) that can be read, or written to, by anynumber of processes. Neither the reader (the subscriber) nor the writer254INTERPROCESS COMMUNICATION MECHANISMS(the publisher) needs to know the identity of any of the other processesthat access the property.Users of properties may publish or subscribe to them, using a singlecommon API; kernel-side usage needs other APIs that we do not discusshere.

There is one high-level abstraction that a developer implementingproperty usage should be aware of: RProperty.A property is defined in terms of its category (which denotes a family ofproperties), a key (which indicates a particular property within a category)and a property type.When defining a property, you may also define security policies forread and write operations on it. If you do, the property can only be setor read by a process that has been granted those security policies. Onceit has been defined, a property’s lifetime is not tied to the lifetime of theprocess (or thread) that defined it.In order to get or set a property, a process needs to know its type,category and key. Provided all the above criteria are satisfied, any processmay set a property.To support programming patterns where either the publisher or asubscriber is able to define a property, it is not a programming error toattempt to access a property before it has been defined.

In such a case,the attempt simply returns an error code.Owning a PropertyAlthough either a publisher or a subscriber may set a property, it iseffectively ‘owned’ by the executable (not necessarily one process) thatdefines it.The main effect of such ownership is that, once defined, the propertycan only be deleted by an instance of the executable that defined it.In order to make this possible, the category of a property must be theSECUREID of the defining process (the value is specified in the MMPfile for the process). If an executable’s process terminates after defininga property, another instance of the same executable may later delete it.This is why the RProperty::Define() and RProperty::Delete()methods are static.class RProperty : public RHandleBase{public:...public:IMPORT_C static TInt Define(TUid aCategory, TUint aKey,TInt aAttr, TInt aPreallocate=0);IMPORT_C static TInt Define(TUid aCategory, TUint aKey,TInt aAttr, const TSecurityPolicy& aReadPolicy,const TSecurityPolicy& aWritePolicy,TInt aPreallocated=0);IMPORT_C static TInt Define(TUint aKey, TInt aAttr,const TSecurityPolicy& aReadPolicy,PUBLISH AND SUBSCRIBE IPCIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_C255const TSecurityPolicy& aWritePolicy,TInt aPreallocated=0);static TInt Delete(TUid aCategory, TUint aKey);static TInt Delete(TUint aKey);static TInt Get(TUid aCategory, TUint aKey, TInt& aValue);static TInt Get(TUid aCategory, TUint aKey, TDes8& aValue);static TInt Get(TUid aCategory, TUint aKey, TDes16& aValue);static TInt Set(TUid aCategory, TUint aKey, TInt aValue);static TInt Set(TUid aCategory, TUint aKey,const TDesC8& aValue);static TInt Set(TUid aCategory, TUint aKey,const TDesC16& aValue);TInt Attach(TUid aCategory, TUint aKey,TOwnerType aType = EOwnerProcess);IMPORT_C void Subscribe(TRequestStatus& aRequest);IMPORT_C void Cancel();IMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_CIMPORT_C};TIntTIntTIntTIntTIntTIntGet(TInt& aValue);Get(TDes8& aValue);Get(TDes16& aValue);Set(TInt aValue);Set(const TDesC8& aValue);Set(const TDesC16& aValue);The following code illustrates how to define and delete a property:const TUid KMyPropertyCat = {0x10013456}; // SAME as UID3/SID in MMPenum TMyPropertyKeys {EMyPropertyInteger};TInt err = RProperty::Define(KMyPropertyCat, EMyPropertyInteger,RProperty::EInt);...TInt delErr = RProperty::Delete(KMyPropertyCat, EMyPropertyInteger);Using PropertiesProperty read and write operations are atomic, therefore it is not possiblefor threads reading a property to get inconsistent data.A property value may be retrieved by specifying its identity each timeit needs to be retrieved:TInt propInt=-1;TInt err = RProperty::Get(KMyPropertyCat, EMyPropertyInteger, propInt);Alternatively, it may be retrieved using a handle created by a call toRProperty::Attach():RProperty tmpProperty;TInt propInt=-1;TInt err = tmpProperty.Attach(KMyPropertyCat, EMyPropertyInteger);...TInt getErr = tmpProperty.get(propInt);256INTERPROCESS COMMUNICATION MECHANISMSThe handle is written into the RProperty instance that is used tomake the call to Attach().

Such a reference is commonly used in orderto subscribe to a property:...// using an active object that has a reference to an RProperty handleiProperty.Subscribe(iStatus);...Subscribe() is an asynchronous function call (with a TRequestStatus& parameter) that requests a notification when the property isnext set by a publisher.

As in this example, it is normally called froman active object that stores the property’s handle in an item (of typeRProperty) in its member data.When you subscribe in this way, the notification results in a call tothe active object’s RunL() which should read the property’s value, usingcode of the form:...// later on, in the active object’s RunL()User::LeaveIfError(iProperty.Get(iPropResult));...The function may then re-subscribe if you need another notificationwhen the property is next set.As you would expect for any asynchronous service that is accessedfrom an active object:• subscription results in a single notification of when a property is nextset• subscribing to a property for a second time without an interveningGet() call is a programming error that panics the subscriber• when you no longer need to be notified of changes to the property,you must cancel any outstanding subscription.As with most R-classes, you must call RProperty::Close() whenyou are done with an RProperty instance.DeterminismThe publish and subscribe mechanism is designed to allow its behavior tobe deterministic (that is, with bounded execution times and no possibilityof out-of-memory errors).

However, in order to achieve deterministicbehavior, you have to ensure that your usage conforms with the followingconditions:• when defining a property, always call Define() with its aPreallocate parameter set to a value of 1MESSAGE QUEUE IPC257• always attach to properties (this ensures that the associated kernelobjects are pre-allocated and makes all operations time-bound)• if a property stores its data in a byte array, always use an array whosesize does not exceed KMaxPropertySize• make sure that the capabilities of a process match the security policiesof the property.8.4 Message Queue IPCMessage queues are sized at the time of creation and provide a convenientway to send and receive messages asynchronously without defining theidentity of the recipient or even knowing of its existence.Operations on message queues are deterministic but are effectivelyused in a ‘fire and forget’ manner.

The main user-side message queueabstractions that are of interest to a developer are: RMsgQueue andRMsgQueueBase.A message queue is essentially a block of memory in the Symbian OSmicrokernel and each message is effectively a slot in that memory, witha size of up to KMaxLength (currently 256) bytes. When a message isdelivered to a thread it is copied from its slot in the queue into the processspace of the receiving thread.Creating a Message QueueYou must create a message queue before it can be opened by participatingthreads that wish to read from, or write to, it.

A message queue is createdwith a fixed number of message slots, and a fixed number of bytes foreach message. Note that the message size must be a (nonzero) multipleof 4 bytes and must not exceed KMaxLength, otherwise the creationoperation panics the client.You can create global or local message queues. A global messagequeue can be named and is publicly visible from other threads:RMsgQueueBase tmpQ;TInt err = tmpQ.CreateGlobal(KMyQueueNameLit, KMyQueueSlots, KSlotSize);It can also be nameless (but still accessible by other processes):RMsgQueueBase tmpQ;TInt err = tmpQ.CreateGlobal(KNullDesC, KMyQueueSlots, KSlotSize);A local message queue is only visible to the current process:RMsgQueueBase tmpQ;TInt err = tmpQ.CreateLocal(KMyQueueSlots, KSlotSize);258INTERPROCESS COMMUNICATION MECHANISMSAll the above operations open a handle (the RMsgQueueBase instance)to the created message queue.You can also create a message queue in the ways described above,but using the templated RMsgQueue class instead of RMsgQueueBase.RMsgQueue’s template parameter defines the message type for the queue.Using RMsgQueue is the preferred option since it adds type-safety, aswell as enforcing the limit on the size of a message.

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

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

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

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