【问题标题】:Communication between parent and child process using pipe in c++在 C++ 中使用管道在父子进程之间进行通信
【发布时间】:2021-10-01 14:38:22
【问题描述】:

我想解决这个问题,但我无法接受输入消息:

创建一个执行以下操作的程序:

1.创建父子进程

2.父进程从键盘读取一个数字并发送给子进程

3.孩子计算给定的数字是否为素数并将结果打印在屏幕上

这是我的代码:

#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

【问题讨论】:

  • @Gal 这不是 read 的工作方式......它应该返回 4 个字节。
  • 是的,运行时会发生什么?
  • 当我运行程序时,它不接受 num 的输入值。它采用值“1”而不是输入值。这就是它计算“1”值的原因。

标签: c++ pipe


【解决方案1】:

将管道与叉子一起使用并不难,但您必须遵守一些规则:

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

【讨论】:

  • 您对代码进行了重要更改,但未对其进行解释(即,在未分配/写入 num 的情况下读取 num 而不是 buffer)。
  • @1201ProgramAlarm:我希望从我的评论中可以清楚地看出,父母的变化并没有反映在孩子身上……老实说,我猜不出为什么 OP 在这里使用了缓冲区,所以我也无法解释为什么他们不应该...
  • 但是这个改变并没有改变结果
猜你喜欢
  • 1970-01-01
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-16
  • 1970-01-01
相关资源
最近更新 更多