c++ - 通过管道传递整数

标签 c++ linux

我在通过管道 n Linux 发送整数或整数数组时遇到问题,首先我尝试发送整数,请看这段代码:

#include <unistd.h>
#include<iostream>
#include<cstdlib>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;

int main()
{

    int count = 10 ;
    //cout <<"Enter a digit : ";
    //cin >> count ;
    cout<<"\n";

    int pfd1[1];
    pipe(pfd1);    

    int a=fork();
    if(a==0)
    {    
        close(pfd1[0]);
        write(pfd1[1],&count,sizeof(count));
        close(pfd1[1]);
        exit(0);
    }
    else
    {   
        wait(NULL);
        int n =0;
        close(pfd1[1]);       
        read(pfd1[0],&n ,sizeof(n));
        close(pfd1[0]);
        cout <<"N from parent = "<<n<<"\n\n";
    }
    return 0;
}

输出:

N from parent = 4

输出应该是 10 与声明的相同,但它给了我 4,即使我取消注释注释代码以便用户输入一个数字,输出始终是 4,而它应该是用户输入的数字。

这里有什么问题?如果我想发送整数数组怎么办?

最佳答案

您将超出数组边界,您应该将 pfd1 声明为

int pfd1[2];

关于c++ - 通过管道传递整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30310589/

相关文章:

c - 理解 C 中的 printf

c - 多线程 Linux 程序没有给出预期的输出

linux - 无法从/usr/local/lib访问本地共享库

linux - 生成文件 g++ : fatal error: no input files

c++ - 通过 pybind11 从 C++ 使用 scipy

c++ - 使用 GStreamer 和 wxPanel 播放视频

c++ - 在我的类(class)中使用 < 的 sort() 问题

linux - 我们可以在没有安装任何操作系统的情况下安装 KVM 吗?

c++ - 教科书中的指针示例让我感到困惑

c++ - 如果玩家输入无效选择,我如何防止程序继续?