简体   繁体   English

在 C 中从管道写入和读取整数

[英]Writing and Reading integers from a pipe in C

I am trying to understand using pipes in C, specifically writing and reading integers.我试图理解在 C 中使用管道,特别是写入和读取整数。 I have a parent process that creates 3 child processes.我有一个创建 3 个子进程的父进程。 Two of the child processes calculate numbers and write them to a pipe.两个子进程计算数字并将它们写入管道。 The third process reads from both pipes and then displays.第三个进程从两个管道中读取,然后显示。 Sounds simple right?听起来很简单吧?

I found this post: How to send integer with pipe between two processes!我找到了这篇文章: 如何在两个进程之间用管道发送整数! on how to send integers through pipes and followed it, but I am not producing the correct output.关于如何通过管道发送整数并遵循它,但我没有产生正确的输出。

Edit: for further clarification, I initiate the pipes like so:编辑:为了进一步澄清,我像这样启动管道:

int p1[2]; //pipe1 
int p2[2]; //pipe2
pipe(p1); //intialize pipe1 for between process 1 & 3
pipe(p2); //initialize pipe2 for between process 2 & 3

After some debugging, I notice that the wrong number is being written to the pipe.经过一些调试,我注意到错误的数字被写入管道。 This is how I am writing an int to the pipe:这就是我向管道写入 int 的方式:

int c0 = 18;
write(p2[1], &c0, sizeof(c0));

and this is how I am reading:这就是我的阅读方式:

int disp[4];
read(p1[0], &disp[0], sizeof(disp[0]));

and so on until the array is full.依此类推,直到数组已满。

Now instead of writing something like 14 to the pipe, it writes a large number like 17462. I am assuming that it is writing the address, right?现在,不是向管道写入 14 之类的内容,而是写入了 17462 之类的大数字。我假设它正在写入地址,对吗? If so, how would I write the actual integer to the pipe?如果是这样,我将如何将实际整数写入管道? Should I remove the '&' from the statements, because doing that gives me errors about casting.我是否应该从语句中删除“&”,因为这样做会给我带来有关转换的错误。 Any tips, advice, comments are always appreciated.任何提示,建议,评论总是受到赞赏。 Thanks.谢谢。

You probably need to get write locks on the pipe.您可能需要在管道上获得写锁。

If process 1 and process 2 writes to the pipe simultaneously, you might get bytes mixed in the pipe such that the resulting read will be some strange number you've never seen.如果进程 1 和进程 2 同时写入管道,您可能会在管道中混合字节,从而导致读取的结果将是一些您从未见过的奇怪数字。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM