首页 > 解决方案 > 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;
}

this my result of run

标签: c++pipe

解决方案


使用管道和叉子并不难,但你必须遵守一些规则:

  • 每个部分都应该关闭它不使用的手柄。不做是未来问题的关键
  • 从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管道和来自管道......)


推荐阅读