通过管道传递整数

Passing integer through a pipe

本文关键字:整数 管道      更新时间:2023-10-16

我有问题通过管道发送整数或整数数组在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<<"nn";
    }
    return 0;
}
输出:

N from parent = 4

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

怎么了?如果我想发送一个整数数组呢?

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

int pfd1[2];