1  // Copyright 2015 The Go Authors. All rights reserved.
       2  // Use of this source code is governed by a BSD-style
       3  // license that can be found in the LICENSE file.
       4  
       5  #include <errno.h>
       6  #include <stdio.h>
       7  #include <stdlib.h>
       8  #include <string.h>
       9  #include <time.h>
      10  #include <unistd.h>
      11  
      12  #define fd (30)
      13  
      14  // Tests libgo2.so, which does not export any functions.
      15  // Read a string from the file descriptor and print it.
      16  int main(void) {
      17    int i;
      18    ssize_t n;
      19    char buf[20];
      20    struct timespec ts;
      21  
      22    // The descriptor will be initialized in a thread, so we have to
      23    // give a chance to get opened.
      24    for (i = 0; i < 200; i++) {
      25      n = read(fd, buf, sizeof buf);
      26      if (n >= 0)
      27        break;
      28      if (errno != EBADF && errno != EINVAL) {
      29        fprintf(stderr, "BUG: read: %s\n", strerror(errno));
      30        return 2;
      31      }
      32  
      33      // An EBADF error means that the shared library has not opened the
      34      // descriptor yet.
      35      ts.tv_sec = 0;
      36      ts.tv_nsec = 10000000;
      37      nanosleep(&ts, NULL);
      38    }
      39  
      40    if (n < 0) {
      41      fprintf(stderr, "BUG: failed to read any data from pipe\n");
      42      return 2;
      43    }
      44  
      45    if (n == 0) {
      46      fprintf(stderr, "BUG: unexpected EOF\n");
      47      return 2;
      48    }
      49  
      50    if (n == sizeof buf) {
      51      n--;
      52    }
      53    buf[n] = '\0';
      54    printf("%s\n", buf);
      55    return 0;
      56  }