/* Copyright (c) 2001-2004 by SoftIntegration, Inc. All Rights Reserved */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main() {
  int oldSTDERR; // store standard error control
  char *fname = "dup2_1.txt";
  FILE *stream;
  oldSTDERR = dup(2); // save original standard error handler

  fprintf(stderr, "This is a testing message in stderr\n");
  stream = freopen(fname, "w+", stderr);   // rediect stderr to fname 
  if(stream != NULL) {
     fprintf(stderr, "This is a testing message in dup2_1.txt\n");
  }
  fflush(stderr);
  dup2(oldSTDERR, 2); // recover standard error control
  close(oldSTDERR);
  fprintf(stderr, "This is a testing message in stderr again\n");
  system("cat dup2_1.txt");
  remove("dup2_1.txt");
  return 0;
}
