开发者

How can a child process return two values to the parent when using pipe()?

开发者 https://www.devze.com 2023-04-07 22:47 出处:网络
I have my child process开发者_如何学JAVA counting the frequency of words from a text file. I am using pipe() for IPC. How can the child process return both the word name and the word frequency to the

I have my child process开发者_如何学JAVA counting the frequency of words from a text file. I am using pipe() for IPC. How can the child process return both the word name and the word frequency to the parent process? My source code is in C and I am executing it in a UNIX environment.


Write the two values to one end of the pipe in the child, separated by some delimiter. In the parent, read from the other end of the pipe, and separate the content using the delimiter.


Writes to a pipe up to the size of PIPE_BUF are atomic (included in limits.h), therefore you can easily pack your information into some type of struct, and write that to the pipe in your child process for the parent process to read. For instance, you could setup your struct to look like:

struct message
{
    int word_freq;
    char word[256];
};

Then simply do a read from your pipe with a buffer that is equal to sizeof(struct message). That being said, keep in mind that it is best to only have either a single reader/writer to the pipe, or you can have multiple writers (because writes are atomic), but again, only a single reader. While multiple readers can be managed with pipes, the fact that reads are not atomic means that you could end up with scenarios where messages either get missed due to the non-deterministic nature of process scheduling, or you get garbled messages because a process doesn't complete a read and leaves part of a message in the pipe.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号