Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // avp 2014 save-restore stderr by fd
- #ifdef __cplusplus
- #include <iostream>
- using namespace std;
- #endif
- #include <stdio.h>
- #include <stdlib.h>
- #include <unistd.h>
- #include <fcntl.h>
- #include <errno.h>
- int hide_stderr (const char *dst)
- {
- int fd, efd = fileno(stderr), save = dup(efd), olderr = errno;
- if (dup2(fd = open(dst, O_WRONLY | O_CREAT | O_TRUNC, 0664), efd) == -1) {
- olderr = errno;
- close(save);
- save = -1;
- }
- close(fd);
- errno = olderr;
- return save;
- }
- int rest_stderr (int savefd)
- {
- int drc = dup2(savefd, fileno(stderr));
- if (drc != -1)
- close(savefd);
- return drc;
- }
- int main (int ac, char *av[])
- {
- #ifdef __cplusplus
- cerr << "c++ 1\n";
- #endif
- perror("xaxa");
- #if 0
- int fd, stderrfd = fileno(stderr), save = dup(stderrfd);
- printf ("stderrfd: %d save: %d\n", stderrfd, save);
- printf ("dup2 xaxa to %d\n",
- dup2(fd = open("xaxa", O_WRONLY | O_CREAT | O_TRUNC, 0664), stderrfd));
- close(fd);
- printf ("fd = %d\n", fd);
- #else
- int save = hide_stderr(av[1] ? av[1] : "/dev/null");
- #endif
- perror("xoxo");
- errno = 0;
- fprintf (stderr, " after perror %m\n");
- #ifdef __cplusplus
- cerr << "c++ 2\n";
- #endif
- #if 0
- int drc = dup2(save, stderrfd);
- if (close(save) == -1)
- perror("close");
- else
- perror("success");
- #else
- int drc = rest_stderr(save);
- #endif
- if (drc == -1)
- perror("dup2");
- else
- perror("xixi");
- #ifdef __cplusplus
- cerr << "c++ 3\n";
- #endif
- printf ("drc = %d\n", drc);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement