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