Peter
Peter

Reputation: 1

`select` on same fd from another thread

I wanna write the same fd from other thread. is it possible? I couldn't get fdset event on select.

on thread_main, I've got "bad file descriptor. what things are wrong here?

<pre>
void *thread_main(void *arg)
{
    int len = 0;
    int *fd = (int *)arg;
    len = write(fd[0], "a", 1);
    // I've got write...-1-9(Bad file descriptor)
    printf("write...%d-%d(%s)\n", len, errno, strerror(errno));
    len = write(fd[1], "b", 1);
    printf("write...%d-%d(%s)\n", len, errno, strerror(errno));
}
<code>

on the main, there is nothing to read if same fd is set from the thread above.

    int main()
    {
        int fd[2];
        int i;
        int n;
        int state;
        char buf[255];
        fd_set readfds, writefds;
        pthread_t thread;

if ((fd[0] = open("./testfile", O_RDONLY)) == -1) { perror("file open error : "); exit(0); } if ((fd[1] = open("./testfile2", O_RDONLY)) == -1) { perror("file open error : "); exit(0); } pthread_create(&thread, NULL, &thread_main, (void *)fd); memset (buf, 0x00, 255); for(;;) { FD_ZERO(&readfds); FD_SET(fd[0], &readfds); FD_SET(fd[1], &readfds); state = select(fd[1]+1, &readfds, NULL, NULL, NULL); switch(state) { case -1: perror("select error : "); exit(0); break; default : for (i = 0; i < 2; i++) { if (FD_ISSET(fd[i], &readfds)) { while ((n = read(fd[i], buf, 255)) > 0) printf("(%d) [%d] %s", state, i, buf); } } memset (buf, 0x00, 255); break; } usleep(1000); } }

Upvotes: 0

Views: 234

Answers (1)

pilcrow
pilcrow

Reputation: 58589

fd[0] is open read-only (O_RDONLY), but you are trying to write() to it. That is why you fail with EBADF.

Upvotes: 2

Related Questions