Socket programming : why are the behaviors of recv() and read() not the same?
I use select()
to receive data from stdin.
The code is here:
#include <stdio.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
int main()
{
fd_set rfds;
struct timeval tv;
int retval;
char buf[100];
FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1,&rfds,0,0,&tv);
if( retval == -1)
perror("select reset\n");
else if(retval == 0)
printf("timeout\n");
else
{
printf("data available\n");
if(FD_ISSET(STDIN_FILENO, &rfds))
{
//int ret = recv(STDIN_FILENO, buf, sizeof(buf), 0); // ret get -1.
int ret = read(STDIN_FILENO, buf, sizeof(buf)); // ret get correct data.
printf("buf: %s ret: %d\n", buf,ret);
}
}
return 0;
}
开发者_Python百科
In this code, recv()
will always return -1
, but read()
can get correct data.
I find that read()
is equivalent to recv()
with a flags
parameter of 0
. Why then are the behaviors of recv()
and read()
not the same in my code?
Because recv()
is for use on sockets, not generic file descriptors like stdin. Sockets can be treated like any descriptor, but descriptors don't necessarily have a socket behind them (and in the case of stdin, they don't).
In that particular piece of code, I suspect that if you check errno
it will have a value of EINVAL
or similar.
check out man page:
ssize_t recv(int sockfd, void *buf, size_t len, int flags);
精彩评论