c++ - Communication between parent and child process using pipe in c++
问题描述
I wanted to do this problem but I cannot take input message:
Create a program that does the following:
1.Create a parent and a child process
2.The parent process reads a number from keyboard and sends it to the child
3.The child calculates if the given number is prime or not and prints the result on screen
This is my code:
#include <iostream>
#include <unistd.h> // for fork()
#include <string.h> // for strerror()
#include <sys/wait.h>
#include <sys/types.h>
using namespace std;
bool isprime(int number);
int main()
{
int num;
pid_t pid;
int fd[2];
char buffer[100];
pipe(fd);
pid = fork();
//parent process
if (pid > 0)
{
cin>>num;
write(fd[1], &num, sizeof(num));
close(fd[1]);
int status;
//Do not check for errors here
wait(&status);
}
//child process
else if (pid == 0)
{
read(fd[0], buffer, 100);
close(fd[0]);
if (isprime(num))
{
cout<<"number is prime";
}
else
{
cout<<"number is not prime";
}
return EXIT_SUCCESS;
}
else
{
cout << "fork() failed (" << strerror(errno) << ")" << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
bool isprime(int number)
{
if (number < 2)
return false;
if (number == 2)
return true;
for (int i = 2; (i*i) <= number; i++)
{
// Take the rest of the division
if ((number % i) == 0)
return false;
}
return true;
}
解决方案
使用管道和叉子并不难,但你必须遵守一些规则:
- 每个部分都应该关闭它不使用的手柄。不做是未来问题的关键
- 从fork开始,一个进程的变化不会反映在另一个进程中
你的代码应该变成:
...
//parent process
if (pid > 0)
{
close(fd[0]); // close the part that only the other process will use
cin>>num;
write(fd[1], &num, sizeof(num));
close(fd[1]);
int status;
//Do not check for errors here
wait(&status);
}
//child process
else if (pid == 0)
{
close(fd[1]); // close the part used by the other process
read(fd[0], &num, sizeof(num)); // read into num what the parent has written
close(fd[0]);
...
在现实世界的代码中,您应该检查每次读取是否成功(来自cin
管道和来自管道......)
推荐阅读
- jasmine - 编写具有无限测试规范的测试套件
- javascript - 使用 IntersectionObserver 检测 div 位置变化
- java - 如何每次用数组中的随机元素替换字符串变量中的多个单词?
- html - flex-wrap 没有包裹在容器内
- python - 如何从 Python 中的多值 dict/multi-d 数组创建多个随机数组?
- javascript - 通过从 Javascprit 中的 URL 获取给函数一个参数?
- javascript - 如何在 loadJson 中发送多个值?
- youtube-api - 从 YouTube Content ID API 获取所有资产的报告
- r - R中随着时间的推移连接的路段和交通密度热/等高线图
- javascript - 检查对象子对象在javascript中是否为空