pipes und threads: Bad file descriptor



  • Hallo!

    Bei dem folgenden simplen Programm...

    #include<pthread.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<unistd.h>
    
    void *t1(void *p)
    {
      char *b = "1234567890";
      if(write(*(int*)p, b, 11) == -1)
        perror("write");
    }
    
    void *t2(void *p)
    {
      char *b = new char[11];
      if(read(*(int*)p, b, 11) == -1)
        perror("read");
      printf(b);
      delete[] b;
    }
    
    int main()
    {
      int fd[2];
      if(pipe(fd) == -1)
        {
          perror("pipe");
          exit(1);
        }
    
      pthread_t thread[2];
      pthread_create(&thread[0], NULL, t1, (void*)&fd[0]);
      pthread_create(&thread[1], NULL, t2, (void*)&fd[1]);
    
      pthread_join(thread[0], NULL);
      pthread_join(thread[1], NULL); 
    
      return 0;
    }
    

    ...bekomme ich diese Fehler:

    write: Bad file descriptor
    read: Bad file descriptor

    Warum? Kann man pipes etwa nicht in threads verwenden?



  • pipe() creates a pair of file descriptors, pointing to a pipe inode, and places them in the array pointed to by filedes. filedes[0] is for reading, filedes[1] is for writing.

    http://linux.die.net/man/2/pipe

    Merkst du was? 😉



  • Ooops. Danke. 😋


Anmelden zum Antworten