Advertisement
avp210159

hide_stderr.c

Mar 28th, 2014
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.52 KB | None | 0 0
  1. // avp 2014 save-restore stderr by fd
  2. #ifdef __cplusplus
  3. #include <iostream>
  4. using namespace std;
  5. #endif
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #include <unistd.h>
  10. #include <fcntl.h>
  11. #include <errno.h>
  12.  
  13. int hide_stderr (const char *dst)
  14. {
  15.   int fd, efd = fileno(stderr), save = dup(efd), olderr = errno;
  16.   if (dup2(fd = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0664), efd) == -1) {
  17.     olderr = errno;
  18.     close(save);
  19.     save = -1;
  20.   }
  21.   close(fd);
  22.   errno = olderr;
  23.   return save;
  24. }
  25.  
  26. int rest_stderr (int savefd)
  27. {
  28.   int drc = dup2(savefd, fileno(stderr));
  29.   if (drc != -1)
  30.     close(savefd);
  31.   return drc;
  32. }
  33.  
  34.  
  35.  
  36. int main (int ac, char *av[])
  37. {
  38. #ifdef __cplusplus
  39.   cerr << "c++ 1\n";
  40. #endif
  41.  
  42.   perror("xaxa");
  43. #if 0
  44.   int fd, stderrfd = fileno(stderr), save = dup(stderrfd);
  45.   printf ("stderrfd: %d save: %d\n", stderrfd, save);
  46.   printf ("dup2 xaxa to %d\n",
  47.       dup2(fd = open("xaxa", O_WRONLY | O_CREAT | O_TRUNC, 0664), stderrfd));
  48.   close(fd);
  49.   printf ("fd = %d\n", fd);
  50. #else
  51.   int save = hide_stderr(av[1] ? av[1] : "/dev/null");
  52. #endif
  53.   perror("xoxo");
  54.   errno = 0;
  55.   fprintf (stderr, " after perror %m\n");
  56. #ifdef __cplusplus
  57.   cerr << "c++ 2\n";
  58. #endif
  59.  
  60. #if 0
  61.   int drc = dup2(save, stderrfd);
  62.   if (close(save) == -1)
  63.     perror("close");
  64.   else
  65.     perror("success");
  66. #else
  67.   int drc = rest_stderr(save);
  68. #endif
  69.   if (drc == -1)
  70.     perror("dup2");
  71.   else
  72.     perror("xixi");
  73.  
  74. #ifdef __cplusplus
  75.   cerr << "c++ 3\n";
  76. #endif
  77.  
  78.   printf ("drc = %d\n", drc);
  79.  
  80. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement