0

I understand that socketpair API can generate a pair of connected sockets. But is it true that socketpair() can generate two same pairs in the same process?

// In the same process
int fd[2];
int r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
printf("fd[0] = %d fd[1] = %d\n", fd[0], fd[1]);

// something else
r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
printf("fd[0] = %d fd[1] = %d\n", fd[0], fd[1]);

If print out the fd pairs, is it possible to see the below result?

fd[0] = 27 fd[1] = 28
fd[0] = 27 fd[1] = 28  // duplicated pairs?

If this is normal behavior, how can we protect from reading after close errors?

// In the same process
int fd[2];
int r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
printf("fd[0] = %d fd[1] = %d\n", fd[0], fd[1]);

// something else
close(fd[0]);  // close the fd[0] (27)

r = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
printf("fd[0] = %d fd[1] = %d\n", fd[0], fd[1]);

read(fd[0]);   // Bad FD error? As it already closed in the code above
Alan
  • 469
  • 10
  • 26
  • 1
    It can happen if (1) socketpair returns an error or (2) the sockets are closed in the "something else" part. It isn't clear what you mean by "protect from reading after close". If you have file descriptor 27 and then you close it and create a new one, it can be 27 again and there's no error in that. – n. m. could be an AI Jul 16 '21 at 16:27
  • In my real code (1) is not true, as my program terminated if `socketpair` return errors. (2) I do have a fd 27 in the second socketpair call, but I also got a bad fd error when I try to read it. I was confused about this issue. Thank you for your comment. – Alan Jul 16 '21 at 16:45
  • 1
    Do you have a [mcve]? There is nothing wrong in the code as posted. The problem is most likely in the omitted portion. – n. m. could be an AI Jul 16 '21 at 17:00

0 Answers0