LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   What is fastest way of exchanging data between child and parent process (https://www.linuxquestions.org/questions/programming-9/what-is-fastest-way-of-exchanging-data-between-child-and-parent-process-655165/)

Zagi 07-11-2008 02:42 PM

What is fastest way of exchanging data between child and parent process
 
Hi,

Does anyone knows what is the fastest way (less CPU usage) of sending data between child and parent process in c/linux.

/thanks,

rjlee 07-11-2008 04:52 PM

Most PCs have one memory bank accessed by all processors, so if all you want is to have both processes see the same data then shared memory is your best bet.

I believe that the preferred way to use shared memory is to mount a ram disk on the hard drive (shmfs or tmpfs), and to have both processes read and write files on that directory (which physically exist in system RAM). That results in understandable and maintainable code, and can be easily ported to other systems (including mainframes, which may have much more complex memory arrangements).

But if minimum CPU is the goal then you may want to skip the virtual filesystem and access shared memory segments directly; there's quite a good tutorial on this here: http://www.cs.cf.ac.uk/Dave/C/node27.html. This is much more code to write than the filesystem approach, but has the advantage that there is no reading or writing to do; the data is simply there for both programs whenever it exists.

I should also note that the most "correct" way to share information is to use a pipe (named or anonymous). This has the advantage that you can't run out of memory: if the process sending information sends too much for the OS to buffer, then it'll simply slow down the sending process until the receiver has processed more. This is even simpler than the RAM disk approach, as it needs no setup other than that which the program can do.

The Documentation Project has further reading on IPC: http://tldp.org/LDP/lpg/node7.html

Hope that helps,

—Robert J Lee

Mr. C. 07-11-2008 04:55 PM

Processes can open shared memory segments. See:

man shmat shmget

It is not necessary to create a file system entry.

jiml8 07-12-2008 12:47 PM

Sharing memory is intrinsically fastest, but you have to be careful to set up a synchronization mechanism between parent and child, to make sure that data is only read/written when it should be, and to make sure your processes don't step on each other.

This will add overhead. You need to study semaphores and spinlocks. Pay particular attention to race conditions and potential non-atomic conditions (conditions that could be interrupted in the middle before completion).


All times are GMT -5. The time now is 03:59 AM.