In the following example we close default
char fname = "/tmp/tst-perror.XXXXXX";
fd = mkstemp (fname);
dup2 (fd, 2);
stderr = fdopen (2, "w");
fd = fileno(stderr);
char *s = "this is a test\n";
n = write(fd, s, strlen(s));
fprintf(stderr, "multibyte string\n");
// fd = open(fname, O_RDONLY);
lseek (fd, 0, SEEK_SET);
n = read (fd, buf, sizeof (buf));
printf("%.*s", (int) n, buf);
this is a test
There is no check on return values from the functions. If it had been there you would have found the error.
Anyway, the issue is:
fd = fileno(stderr); // getting the fd from current stderr fclose (stderr); // closing stderr ... lseek (fd, 0, SEEK_SET); // seeking on fd which was already closed
In the last call and subsequent calls
fd is actually undefined (or rather it references closed file descriptor). Therefore any operation on
fd will fail
EBADF (not valid file descriptor).
Obviously if you include the
fd = open(...) again,
fd will become valid and the code will work.