Skip to content
This repository has been archived by the owner on Jun 30, 2020. It is now read-only.

Commit

Permalink
Use fstat() to check if there is a socket or not
Browse files Browse the repository at this point in the history
recv/send function can only be applied to a socket.
We can use fstat() function to check if the fd is a socket or not.
If so, we would like to use recv/send function to replace read/write.
Related to:#30
Signed-off-by: Ke Zhao <[email protected]>
  • Loading branch information
Ke Zhao committed Apr 4, 2019
1 parent 72f2c71 commit 950ddf3
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 2 deletions.
13 changes: 12 additions & 1 deletion bin/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
#include "exe.h"
#include "non.h"

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
Expand Down Expand Up @@ -183,12 +184,22 @@ on_conn(options_t *opts, int con, int in, int out, const struct addrinfo *ai)
while (poll(pfds, 2, -1) >= 0) {
char buffer[64 * 1024] = {};
ssize_t ret;
struct stat st;

for (int i = 0; i < 2; i++) {
if (!pfds[i].revents)
continue;

ret = read(pfds[i].fd, buffer, sizeof(buffer));
if (fstat(pfds[i].fd, &st)) {
fprintf(stderr, "Error in fstat. Errno is %d\n", errno);
return -1;
}

if (S_ISSOCK(st.st_mode))
ret = recv(pfds[i].fd, buffer, sizeof(buffer), 0);
else
ret = read(pfds[i].fd, buffer, sizeof(buffer));

if (ret <= 0) {
if (pfds[i].revents != POLLHUP &&
(errno == EAGAIN || errno == EWOULDBLOCK))
Expand Down
14 changes: 13 additions & 1 deletion bin/non.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@

#include "non.h"

#include <sys/stat.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <errno.h>
Expand Down Expand Up @@ -97,8 +99,18 @@ non_write(int fd, void *buf, size_t len)
struct pollfd pfd = { .fd = fd, .events = POLLOUT };
uint8_t *b = buf;
ssize_t ret;
struct stat st;

if (fstat(fd, &st)) {
fprintf(stderr, "Error in fstat. Errno is %d\n", errno);
return -1;
}

if (S_ISSOCK(st.st_mode))
ret = send(fd, buf, len, 0);
else
ret = write(fd, buf, len);

ret = write(fd, buf, len);
if (ret < 0) {
if (errno != EAGAIN)
return ret;
Expand Down

0 comments on commit 950ddf3

Please sign in to comment.