An alternative approach to using the popen() function
is to use named pipes, or FIFOs. The advantage of using them 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 (and avoid 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 those offered by the popen() function, for example, inter-child process communication. For more information about the use of FIFOs, see http:\\www.opengroup.org.
Parent process P.I.P.S. example using FIFOs
The following code shows how FIFOs can be used in P.I.P.S. by the 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 P.I.P.S. example using FIFOs
The following code shows how FIFOs can be used in P.I.P.S. by the 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; }