管道不能 read/write 所有字符

pipe can not read/write all the chars

我正在尝试使用管道将字符数组从一个进程发送到另一个进程,字符正在传递,但不是全部!只是开始的部分。 这是我的代码:

int p1[2], p2[2];

int main()
{
    pipe(p1);

    int f1= fork();

    if(f1 == 0)

    {       
        char ar[100];
        int n = 38;
        for(int i=0;i<n;i++)
        { ar[i] = 'f'; }
        close(p1[0]); //close the read
        write(p1[1],ar,n+1);

    } else if (f1 > 0)

    {
        wait(NULL);
        int f2 = fork();
        if(f2 == 0)

        {   
            char arr2[100];
            close(p1[1]); //close the write
            int m = read(p1[0],arr2,strlen(arr2));
            cout << arr2 << " " << m << endl;   

        } 
        else if (f2 > 0)

        {wait(NULL);}

    }
    return 0;
}

您在未初始化的 char 数组上调用了 std::strlen(),这是您的错误。 std::strlen() 查找数组中第一次出现的空字节及其位置 return。但是数组是未初始化,因此第一次出现空字节未定义

此外,您应该检查库函数的 return 值(pipe()read()write()fork() 等)。