使用 Pipe() 时,子进程如何向父进程返回两个值?

发布于 2024-12-07 01:43:08 字数 106 浏览 1 评论 0原文

我让我的孩子计算文本文件中单词的频率。我正在使用 pipe() 进行 IPC。子进程如何同时返回词名和词频给父进程呢?我的源代码是 C 语言,我在 UNIX 环境中执行它。

I have my child process 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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

似狗非友 2024-12-14 01:43:08

将两个值写入子级中管道的一端,并用某个分隔符分隔。在父级中,从管道的另一端读取,并使用分隔符分隔内容。

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.

︶葆Ⅱㄣ 2024-12-14 01:43:08

写入管道的大小最大为 PIPE_BUF 是原子的(包含在 limits.h 中),因此您可以轻松地将信息打包到某种类型的结构中,并将其写入到子进程中的管道供父进程读取。例如,您可以将结构设置为如下所示:

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

然后只需使用等于 sizeof(struct message) 的缓冲区从管道中进行读取。话虽这么说,请记住,管道最好只有一个读取器/写入器,或者可以有多个写入器(因为写入是原子的),但同样,只有一个读取器。虽然可以使用管道管理多个读取器,但读取不是原子的这一事实意味着您最终可能会遇到消息由于进程调度的不确定性而丢失的情况,或者您得到乱码消息,因为进程未完成读取并将部分消息留在管道中。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文