/*
 *  When open a file the OS give you the first file
 *  descriptor free (i.e. the lower available) so
 *  when you close the stderr and then open a file
 *  the former replace the earlier. This can be a problem.
 *
 *  To test try
 *
 *    $ ./std-err useless-file   2<&1-
 *  
 *  NOTE: this overwrite the file passed as argument. use
 *  with caution.
 *
 *  CREDITS: thanks to Paolo Bonzini and the git mailing list
 *  <http://article.gmane.org/gmane.comp.version-control.git/93716>
 */
#include <stdio.h>
#include <fcntl.h>

int main(int argc, char* argv[]){
  char* fname = "/dev/tty";
  if(argc > 1)
    fname = argv[1];

  int fd = open (fname, O_WRONLY);
  if(fd < 0){
    perror("open");
    return 1;
  }
  FILE *fp;
  fp = fdopen (fd, "w");

  fprintf (fp, "file descriptor %d\n", fd);
  fflush (fp);
  fprintf (stderr, "writing on stderr now\n");

  return 0;
}
