0

I've seen this Question.

It says that we could make a copy of both the file descriptors of stdin and stdout, in order for us to reopen them at a later stage in the program.

My questions:

  • Could we open the file "/dev/tty" in O_WRONLY mode in order to reopen stdout?
  • Is this the correct method of doing it?
  • Is there any similar method to reopen stdin and stderr??
Community
  • 1
  • 1
Abijith Kp
  • 199
  • 1
  • 2
  • 9
  • it says you *should*. not *could*. what's wrong with their proposed solution? – Karoly Horvath Oct 08 '14 at 10:22
  • 1
    While reopening `/dev/tty` will work, it wouldn't handle situation when `std*` never were `/dev/tty`, but rather was redirected to other process/file by calling shell. – keltar Oct 08 '14 at 10:24
  • I've seen using "/dev/null" for reopening stdin, stdout and stderr by just changing the opening modes. Here is that [article](http://www.microhowto.info/howto/cause_a_process_to_become_a_daemon_in_c.html#idp135824). Why was /dev/null used?? – Abijith Kp Oct 08 '14 at 10:36
  • @KarolyHorvath There was no problem with the solution. I myself used that method till now. But the statement at the end was curious, and I wanted to know how it worked. – Abijith Kp Oct 08 '14 at 10:38
  • 1
    It opens null to get valid `std*` descriptors. Reading/writing to null wouldn't fail (but will go nowhere, of course), as opposed to invalid file descriptor. – keltar Oct 08 '14 at 10:41
  • So the daemon process mentioned in the process will not be able to get input from or print output to anywhere!! – Abijith Kp Oct 08 '14 at 10:47
  • Exactly. But it closed descriptors for a good reason, right? – keltar Oct 08 '14 at 10:53
  • I guess. Since the specific daeom process would not like any input or output, it closes its std* file deccriptors and reopen them at /dev/null. – Abijith Kp Oct 09 '14 at 02:18
  • Generally, the parent process is connected to a virtual-terminal or pseudo-terminal, then a child may have its std in/out/err redirected or closed, but the reason it can't just open the terminal again is that it doesn't necessarily know where the terminal is or have permission to open it. You can search for the parents matching std in/out/err, but this would be _very_ local-system-dependent. This is a Unix/Linux situation. If Windows became relevant, you could create a file with CONIN$ or CONOUT$ and it will just plug your file handle back into the Console. – Micah W Jan 26 '20 at 10:54

1 Answers1

1

No, the method you posit is not the correct method. The /dev/tty "device" is your terminal device and it doesn't necessarily hold that that's where your standard output is going.

For example, if you run your program as:

yourprog >output.txt

then opening /dev/tty will not get you your starting standard output (which is the output.txt file).

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953