1

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;
}

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?

1
  • 1
    Actually, it seems you found read() is not equivalent to recv()... Commented Aug 1, 2011 at 3:24

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. After I checked, I got errno code 88 (socket operation on non-socket).
0

check out man page: ssize_t recv(int sockfd, void *buf, size_t len, int flags);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.