[C ++套接字对在写入后未读取(断管错误)

问题描述 投票:0回答:1

我有一个套接字对:

int fds[2];
if (socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, fds) < 0) {
throw string("socketpair failed: ") + strerror(errno);
}

fds [1]用于子级,fds [0]用于父级。

现在我创建文件指针-

sockt = fdopen(fds[0], "r+");

我有这个if陈述:if (write_string(sockt, filename) && read_string(sockt, strstate))

应该在if内部输入代码,但read_string函数返回false。

bool
write_string(FILE* f, const string& s)
{
// Saving the string size
size_t len = s.size();
if (len < 253) {
putc(static_cast<unsigned char>(len), f);
// Writing the string
const char* p = s.data();

while (len) {
size_t n = fwrite(p, 1, len, f);
if (n == 0) {
    // EOF.
    return false;
}
p += n;
len -= n;
}

return true;
}

这是read_string():

bool
read_string(FILE* f, string& s)
{
// Extracting the length of the string
int ch = getc(f);
if (ch < 0) return false; // ch becomes -1 here, and hence the function doesn't proceed ahead.
:
:

为什么getc()返回-1。是-1吗?

  • 文件名包含文件名(例如-/home/parth/libarchive_examples/libarchive_text.odt)
  • filename.data()以字符串形式返回名称(/home/parth/libarchive_examples/libarchive_text.odt)
  • len的值小于250且大于0-根据文件名,大约为50-70个字符。

可复制版本

#include <iostream>
#include <cstdio>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <fstream>

using namespace std;

bool
write_string(FILE* f, const string& s)
{
    // Saving the string size
    size_t len = s.size();

    cout<<len<<endl;
    if (len < 253) {
     putc(static_cast<unsigned char>(len), f);
    }
// Writing the string
    const char* p = s.data();

    while (len) {
      size_t n = fwrite(p, 1, len, f);
      if (n == 0) {
        // EOF.
        return false;
      }
      p += n;
      len -= n;
    }

    return true;
}

bool
read_string(FILE* f, string& s)
{
    // Extracting the length of the string
    int ch = getc(f);
    cout<<"ch="<<ch<<endl; // displays -1 here and hence returns false
    if (ch < 0) return false;

    //Other code
    cout<<endl<<"here";
    return true;
}

int main()
{
  string strstate;
  string filename="/home/parth/libarchive_examples/libarchive_text.odt";
  int fds[2];
  int a = socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, fds);

  pid_t child = fork();
    if (child == 0) {

    // Child process.
    close(fds[0]);
    cout<<"In child"<<endl;
    }
  close(fds[1]);

  FILE* sockt = fdopen(fds[0], "r+");

  if (write_string(sockt, filename)&& read_string(sockt, strstate) )
  {
    cout<<"Inside if"<<endl;
  }
  cout<<"After if"<<endl;
  return 0;
}

编辑

  • 我发现getc()在EOF以及遇到错误时返回-1。在使用feof(sockt)进行进一步检查时,我发现没有遇到EOF,因此在使用getc()时必定会出现错误。

  • strerror(errno)给出Broken Pipe

c++ sockets ipc unix-socket socketpair
1个回答
0
投票

正如Manuel所说,您正在尝试读取和写入同一套接字。这很容易解决,只需在调用fork之后用以下代码替换代码即可:

  if (child == 0) {

    // Child process.
    close(fds[0]);
    fds [0] = fds [1];
    cout<<"In child"<<endl;
  }
  else
    close(fds[1]);

Live demo

© www.soinside.com 2019 - 2024. All rights reserved.