【问题标题】:pipe can not read/write all the chars管道无法读取/写入所有字符
【发布时间】:2015-05-15 10:44:35
【问题描述】:

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

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;
}

【问题讨论】:

  • 您不会终止您发送/接收的“字符串”。此外,如果 read 失败 (m == -1) 则缓冲区的内容未指定。

标签: c++ linux ubuntu pipe fork


【解决方案1】:

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

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

【讨论】:

  • 那么我怎样才能通过 strlen()?我不能保持不变,因为在实际程序中我正在从文件中读取字符
  • 您可以先通过管道发送并存储它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多