c - 将随机生成的值从子进程发送到父进程
问题描述
我已经编写了一个代码,它使用 rand() 在子进程中生成一个随机数...我需要使用 pipe() 将此随机值发送到父进程。当我使用 read() 和 write() 时,父级收到的值是 0 而不是随机数。
我没有收到任何错误,只是输出是收到的值是:0。
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#include<fcntl.h>
int main ()
{
pid_t Cpid;
int fd[2];
int rVal;
//pid will store the value of fork()
Cpid = fork();
pipe(fd);
if( Cpid == 0)
{
//CHILD
rVal = rand()%100;
;
//this is in child process
close (fd[0]);
rVal = rand()%100;
write(fd[1], &rVal,sizeof (rVal));
close (fd[1]);
printf(" Child Pid : %d sending random value : %d to parent : %d\n",
getpid(), rVal, getppid());
}
else if(Cpid != 0 )
{
printf (" Parent PID : %d\n", getpid());
//this is the parent process
close(fd[1]);
read(fd[0], &rVal, sizeof(rVal));
printf(" value recieved is : %d\n", rVal);
close(fd[0]);
printf(" value recieved by parent : %d\n", rVal);
}
return 0;
}
解决方案
代码应在分叉子代之前设置管道。否则,父母和孩子将使用不同的管道,并且将无法相互交谈。
int main ()
{
pid_t Cpid;
int fd[2];
// Create the pipe BEFORE forking.
pipe(fd);
//pid will store the value of fork()
Cpid = fork();
if( Cpid == 0)
.. REST OF CODE ~~~
推荐阅读
- regex - 如何通过正则表达式找到字符串中左大括号对应的右大括号?
- javascript - 如何从外部 JavaScript 触发 Vue.js 方法
- android - 有什么方法可以计算用户在我的社交媒体应用程序上访问的每个帖子上花费了多少时间
- swift - 从“xx”类型的抛出函数到非抛出函数类型“xx”的无效转换
- c# - 如何提取阿拉伯语中两个固定字符串之间的数字?
- r - 如何使用带有更新参数的`call()`?
- html - 无法更改覆盖文本的颜色
- javascript - React Redux 状态在渲染另一个组件后停止更改
- elasticsearch - 为什么在Elasticsearch中搜索A找不到内容,但是AA可以
- sql - as.character(query) 中的错误:无法将类型“闭包”强制转换为“字符”类型的向量