S60 Open C
Open C Tips and Tricks

Open C Tips and Tricks

Table of Contents

Symbian OS Porting tips
Dynamic library loading on Symbian OS pre v9.3
Alternatives to fork() and exec() for creating child processes
Parent and child with no IPC ­ use posix_spawn()
Parent and child IPC using a single pipe ­ use popen()
Parent and child IPC using named pipes or FIFOs ­ use mkfifo()
Forking without exec() ­ use posix_spawn() or pthreads
Little or no state data passed to child ­ use posix_spawn()
A large amount of data passed to child ­ use pthreads
exec without forking ­ use posix_spawn()
Signals
Exception Handling
Abnormal Process Termination
Asynchronous I/O
IPC with signals

 


Symbian OS Porting tips

 


Dynamic library loading on Symbian OS pre v9.3

The Symbian OS v9.3 kernel supports all functionalities of P.I.P.S. libraries - referred to as "P.I.P.S.- ready".

Pre v9.3 the kernel only supports the Symbian OS- standard ordinal lookup in DLLs; it does not support symbolic lookup. Thus the function dlsym() cannot be used with a symbolic name. To overcome this restriction, pass the function's ordinal number as symbol parameter refer the library's list of exports (the DEF file) for the function's ordinal number. For example, instead of: dlsym(&handle, "foo") use dlsym (&handle, "3") where the function foo() has ordinal 3.

 


Alternatives to fork() and exec() for creating child processes

There is no support for fork() and exec() APIs because it requires large changes in the kernel. For example, duplicating the address space of an existing process was not considered in the Symbian OS kernel design, and retrofitting this would be difficult. exec() would require a change to the loader (the only way to load a process image into memory) and associated kernel changes.

However, there are industry-standard alternatives to these APIs which are supported by P.I.P.S. They are:

 


Parent and child with no IPC ­ use posix_spawn()

This scenario occurs where the parent process creates a child process, but there is no communication between the parent and child (except where the parent may wait for termination of the child process, for example via use of the waitpid() function). This can happen when a new process is created to handle a particular event. Once the child process has completed the event in question, the parent process blocks whilst it waits for the child to terminate.

Instead of using the two-stage fork() and exec() combination, use the single posix_spawn() API call. For more detailed information on the posix_spawn() function, consult the UNIX man pages. The following example shows how the creation of a child process would be implemented using the fork() and exec() functions. Note that header files have been omitted for clarity.

int main(int argc, char *argv[])
{
pid_t Childpid = fork();
if (Childpid == 0)
{
// Running in Child process
// exec() to replace the child
// process executable
char execFileName[] =
"/root/PortDoc/Example0_c/Posix/
child/ChildProg";
execl(execFileName, NULL);
}
else
{
// Running in parent process
// Wait for the child process to
// terminate
waitpid(Childpid, NULL, 0);
printf("\r\n*** Child process
finished ***\r\n");
}
return EXIT_SUCCESS;
}

The following code shows how the above example can be modified to use posix_spawn() function in the P.I.P.S. environment:

int main(int argc, char *argv[])
{
pid_t Childpid;
char execFileName[] =
"/root/PortDoc/Example0_c/Symbian
/child/ChildProg";
int RetVal = posix_spawn
(&childpid, execFileName, NULL,
NULL, NULL, NULL);
(void) waitpid(Childpid, NULL, 0);
printf("\r\n*** Child process finished
***\r\n");
return EXIT_SUCCESS;
}

 


Parent and child IPC using a single pipe ­ use popen()

This scenario occurs where the parent process creates a child process, and the parent communicates with the child using a single pipe.

Instead of using the two-stage fork() and exec() combination, use single popen() function as defined in stdio.h. Rather than using a pipe for IPC mechanism, parent process will communicate with child process using stream returned by the popen() call, while the child process's input or output is via the stdin/stdout streams. If the parent process requires a file descriptor, it can be obtained by using the fileno() API call. For more details on the popen() function consult the UNIX man pages.

The following example shows how the standard fork() and exec() combination can replaced with popen() and fileno().

// This is the listing for the parent process
int main(int argc, char *argv[])
{
// Create child process using popen().
// Child process writes to the Parent
// therefore "r" parameter.
FILE* ChildProcessStream =
popen("/root/PortDoc/Example1_c/
Symbian/Child/ChildProg", "r");
if (ChildProcessStream == NULL)
{
printf("\n Failure to create
40645_PIPS_AEC.qxd:PIPS 2/2/07 09:20 Page 21
17
childprocess with popen()\n");
return EXIT_FAILURE;
}
else
{
// Use a file descriptor rather than
// a stream
int ChildProcessFD =
fileno(ChildProcessStream);
// Create a receive buffer, and zero
// contents before receiving.
char RxBuffer[100];
memset(RxBuffer, 0, sizeof(RxBuffer));
// Wait for data from the child
// process. Child sends a string.
int nbytes = read(ChildProcessFD,
RxBuffer, sizeof(RxBuffer));
// printf is slightly different from
// the POSIX example to verify that
// the data output to the screen
// is done by the parent process.
printf("\nMessage Received by
Parent=%s", RxBuffer);
// Wait for Child Process to complete
pclose(ChildProcessStream);
}
return EXIT_SUCCESS;
}

 


Parent and child IPC using named pipes or FIFOs ­ use mkfifo()

An alternative to using the popen() method is to use named pipes, or FIFOs. The advantage of using named pipes over the popen() mechanism is that they allow the code in both the parent and child processes to continue to use file descriptors for communication rather than streams (including the modification to the stdin/stdout streams of the child process).

In addition, since each created FIFO is referenced as a file in the file system, FIFOs allow for more complicated IPC schemes than that offered by the popen() method, for example, inter-child process communication. For more details on the use of FIFOs consult the UNIX mkfifo() man pages.

Note: Parent and child processes should synchronize, and open for read must happen before open for write.

The following examples show how FIFOs can be used in the P.I.P.S. environment: // parent process

int main(int argc, char *argv[])
{
char fifoFileName[] =
"/root/PortDoc/Example2_c/Symbian/
fifofile";
int fifoResult =
mkfifo(fifoFileName, S_IXGRP);
if(fifoResult == -1)
{
// fifo creation failure.
printf("\n*** failure mkfifo
***\n");
return EXIT_FAILURE;}
else
{
// FIFO creation successful.
// Spawn the child process.
pid_t Childpid;
char execFileName[] =
"/root/PortDoc/Example2_c/Symbian/
ChildProg";
int RetVal=
posix_spawn(&Childpid, execFileName,
NULL, NULL, NULL, NULL);
if (RetVal != 0)
{
printf("\n*** failure
posix_spawn ***\n");
return EXIT_FAILURE;
}
else
{
// Open the FIFO. Parent reads
// from the FIFO
int ReadFifoFd =
open(fifoFileName, O_RDONLY);
if (ReadFifoFd == -1)
{
// Failed to open the Fifo
printf("\n*** failure Fifo
Open ***\n");
return EXIT_FAILURE;
}
else
{
// create a receive buffer and clear
char RxBuffer[100];
memset(RxBuffer,0, sizeof(RxBuffer));
// Wait for data from the child
// process. Child sends a string.
int nbytes =
read(ReadFifoFd, RxBuffer,
sizeof(RxBuffer));
printf("\nMessage Received by
Parent=%s", RxBuffer);
// Close the FIFO
(void) close(ReadFifoFd);
}
// wait for the child process to finish
(void) waitpid(Childpid, NULL, 0);
// unlink the FIFO
unlink(fifoFileName);
}
}
return EXIT_SUCCESS;
}
// child process
int main(int argc, char *argv[])
{
char fifoFileName[] =
"/root/PortDoc/Example2_c/Symbian/
fifofile";
// Open the FIFO. child writes to parent
int WriteFifoFd =
open(fifoFileName, O_WRONLY);
if (WriteFifoFd == -1)
{
// Failed to open the Fifo
printf("\n*** child failure Fifo
Open ***\n");
return EXIT_FAILURE;
}

else
{
// create a message to send.
char TxMsg[] = "Hello Parent\n";
// Wait for data from the child
// process. Child sends a string.
write(WriteFifoFd, TxMsg, sizeof(TxMsg));
// close the FIFO
(void) close(WriteFifoFd);
}
return EXIT_SUCCESS;
}

 


Forking without exec() ­ use posix_spawn() or pthreads

A UNIX system may create a child process via a fork(), which will not make a subsequent exec() call. The result of this is that the parent and child processes run the same executable. The child may communicate with the parent via pipes, etc. One example of a system which does this is the email software program Exim. In addition to forking without exec(), it can re-exec itself to regain dropped root privileges.

The issues that such systems encounter when porting to the P.I.P.S. environment fall into two categories:

 


Little or no state data passed to child ­ use posix_spawn()

The first issue occurs where little or no data is passed to the child process on the fork() operation. Many examples of this exist in pre/post forking of listening sockets in TCP server applications, for example, in the MPM prefork module of the APACHE server. More details are available at httpd.apache.org/docs/2.2/mod/prefork.html.

This can be resolved by using the posix_spawn() operation, and passing any data using the argv parameters. For more details consult the UNIX man page for posix_spawn().

Note: Some argv parameters must be used to distinguish the behavior of the parent process from the subsequent behavior of the child when the main() function is called, that is, the behavior of the child cannot be identical to that of the parent.

 


A large amount of data passed to child ­ use pthreads

The second issue occurs where there is too much data to be passed across to child process via the posix_spawn() call. A common work-around used in systems where fork() is not available is to use POSIX threads (pthreads). These pthreads will execute in the same process and share the memory space of that process, that is, they can share the same data objects.

One critical difference between using pthreads and fork() is that fork() creates copies of the parent's data objects in the child. These data objects can then be modified independently between the processes. However, when using pthreads, these data objects are shared and therefore extra care is required when accessing these objects if their values can change, for example, use of mutexes, semaphores, etc.

 


exec without forking ­ use posix_spawn()

A UNIX program may exec without forking. The result is that the calling process executes another binary, but has inherited certain properties, for example, file descriptors. The P.I.P.S. environment equivalent would be to call posix_spawn() and pass any inherited data via argv parameters.

Note that if a parent process is waiting for the child to terminate, then termination of the newly created task must be synchronized. Therefore a waitpid() call should follow the posix_spawn() call so that it does not exit prematurely. Otherwise exit() can be called after the posix_spawn() call.

If the process which formerly exec'd and which now uses posix_spawn() stores its PID (e.g. in the file system) to allow other processes to target it, then care must be taken to store the relevant PID as the PID for the newly spawned process may need to be stored instead.

 


Signals

The P.I.P.S. environment does not support signals. The Symbian kernel could function as a signal barrier in much the same way as in UNIX, that is:

  1. Don't handle signals until leaving the kernel.
  2. Introduce a new interruptible-sleep state, and choose the needed places.

The Symbian kernel however, by design does not provide as many services as the UNIX kernel ­ instead many important services are accessed via client/server IPC (for example, the file and socket server).

In P.I.P.S. environment, many POSIX library functions that would, on UNIX, map to system calls, are built out of IPC calls and user space operations. These have no innate protection against interruption by signals, except inside the kernel to send/receive IPC messages. This is a problem because many coding idioms in Symbian OS (especially IPC) are not re-entrant, even if they are thread-safe. Therefore P.I.P.S. functions are likely to be unsafe in the presence of signals. This is explained with an example.

The following code shows a possible implementation of the read() function.

ssize_t read(int fd, void *buf, size_t count)
{
RFile *file = <RFile corresponding to fd>
TPtr8 des(buf, count);
TInt r = file->Read(des);
if (r == KErrNone)
return des.Length();
else
return -1; // should also set errno
}

On first impression this appears to be re-entrant. However, read() is a synchronous IPC call. Unwrapping the read() yields the code below.

ssize_t read(int fd, void *buf, size_t count)
{
RFile *file = <RFile corresponding to fd>
TPtr8 des(buf, count);
TRequestStatus s = KRequestPending;
TInt r = Exec::SessionSendSync(handle,
EFileRead, args, &s);
if (r == KErrNone)
{
User::WaitForRequest(s);
r = s.Int();
}
if (r == KErrNone)
return des.Length();
else
return -1; // should also set errno
}

If the client executing this code receives a signal amidst running Exec::SessionSendSync. This is a kernel function and will not be interrupted, but when returns to user space the signal will fire before the client get as far as User::WaitForRequest. This will be handled correctly unless the signal handler happens to make a synchronous file server call. Exec::SessionSendSync uses a single, per-thread message object to store the message. This is safe, because a thread can only be running one synchronous call at a time. But when the signal handler comes to access a file, the message object for the current thread will already be in use, and the kernel will panic the client.

 


Exception Handling

If a signal handler is present to catch any exception signal, the handler will tidy up before stopping the process. Therefore, when porting code to P.I.P.S., any such signal handling functionality should be removed.

 


Abnormal Process Termination

Abnormal process termination occurs when an external agent sends an event to that process to stop it, for example, a user typed<CTRL-C> at the keyboard. The scenario resembles exception handling, that is, the signal handler is unlikely to do very much. In addition, when executing in a Symbian environment, no such mechanism exists for user interaction. Therefore, when porting code to P.I.P.S., any such signal handling functionality should be removed.

 


Asynchronous I/O

The P.I.P.S. environment lacks support for signals, means that it do not support asynchronous I/O (unless the relevant Symbian API is used directly). Asynchronous I/O works by effectively multi-threading an application. It is started by calling the relevant API, for example, aio_read()/aio_write(), which initiates the I/O request. Once the I/O has completed, the OS normally sends a signal to the relevant process, which is caught by a relevant signal handler. Under P.I.P.S., I/O must be carried out in a synchronous manner. The I/O should be delegated to a separate thread within the same process. This separate thread can do synchronous I/O and, on completion, inform the main thread.

 


IPC with signals

The P.I.P.S. environment lacks support for signals, means that it do not support IPC with signals. Code which uses signals for IPC should be modified to use either pipes or FIFOs, which should be handled by the main processing loop of the process.


©Nokia 2008

Back to top


All rights reserved. This documentation can be used in the connection with this Product to help and support the user.