summaryrefslogtreecommitdiff
path: root/testsuite/tests/lib-unix/fdstatus.c
blob: 6a052d6e6ce92601c7727844e3cfae50ecc588f6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
/* Check if file descriptors are open or not */

#include <stdio.h>
#include <stdlib.h>

#ifdef _WIN32

#define WIN32_LEAN_AND_MEAN
#include <wtypes.h>
#include <winbase.h>
#include <winerror.h>

void process_fd(char * s)
{
  int fd;
  HANDLE h;
  DWORD flags;

  h = (HANDLE) atoi(s);
  if (GetHandleInformation(h, &flags)) {
    printf("open\n");
  } else if (GetLastError() == ERROR_INVALID_HANDLE) {
    printf("closed\n");
  } else {
    printf("error %d\n", GetLastError());
  }
}

#else

#include <limits.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

void process_fd(char * s)
{
  long n;
  int fd;
  char * endp;
  struct stat st;
  n = strtol(s, &endp, 0);
  if (*endp != 0 || n < 0 || n > (long) INT_MAX) {
    printf("parsing error\n");
    return;
  }
  fd = (int) n;
  if (fstat(fd, &st) != -1) {
    printf("open\n");
  } else if (errno == EBADF) {
    printf("closed\n");
  } else {
    printf("error %s\n", strerror(errno));
  }
}

#endif

int main(int argc, char ** argv)
{
  int i;
  for (i = 1; i < argc; i++) {
    printf("#%d: ", i);
    process_fd(argv[i]);
  }
  return 0;
}