Ashika Umanga Umagiliya
Ashika Umanga Umagiliya

Reputation: 9158

How can I open() and close() STDERR in Perl?

Greetings ,

I can close the STDERR in perl using;

close(STDERR)

and after executing some logic , I want to open it back again. How can I do it?

I tried

open(STDERR,">&STDERR");

and didn't work.

Thanks in advance.

Upvotes: 2

Views: 4107

Answers (3)

PypeBros
PypeBros

Reputation: 2646

STDERR is provided by the parent process. It is not necessarily some regular file, so you'd better keep it open unless you don't plan to write on it anymore. I'd avoid toying with the tty shell command and reopen /dev/pts/XX here, honnestly: that will only lead you into trouble

I guess what you may want to do is prevent some library to produce output on STDERR while it has been designed to do so. To do that, you'll need to keep the file open, but move it around in the list of filehandles. The system call new_file_descriptor = dup(old_file_descriptor) do that in C, after which dup2(some_fd,2) to "activate" some file as stderr and dup2(new_stderr_descriptor,2) to "resume" to the real error output.

Closing one of the dup'd file descriptor should allow you to keep working with the other one, although I'd expect weird things to occur when using sockets, here. (beware, dig manpages and write test cases if needed).

Oh, and btw, the perlfunc manpage for open just show you the perl way to do those dups, although I must confess I don't quite fully understand the subtleties of that syntax:

open my $oldout, ">&STDOUT"     or die "Can't dup STDOUT: $!";
open OLDERR,     ">&", \*STDERR or die "Can't dup STDERR: $!";
# ...

Upvotes: 2

ysth
ysth

Reputation: 98398

dup it first, then dup the dup to reopen it (error checking left as an exercise for the reader, though dealing with errors when STDERR is unavailable can be an exercise in frustration):

open(my $saveerr, ">&STDERR");
close(STDERR);
open(STDERR, ">&", $saveerr);

Note that when you close STDERR you free file descriptor 2; if you open another file and it gets file descriptor 2, any non-Perl libraries you are using may think that other file is stderr.

Upvotes: 10

pascal
pascal

Reputation: 3365

Why do you want to close STDERR?

You could put it aside...

open(FOO, ">/dev/null"); # or ">nul" on Windows
*TEMP = *STDERR;
*STDERR = *FOO;
... then
*STDERR = *TEMP;

Upvotes: 11

Related Questions