user1479376
user1479376

Reputation: 337

Closing the Standard Input

1.what happen in this code :

 close(0)

now, there is no way to read input?

2.What about this:

close(0)
dup(1)

I think now the input coming from the standard output but what is mean?

Upvotes: 0

Views: 919

Answers (2)

anatolyg
anatolyg

Reputation: 28251

  1. It seems that there is no way to read the input. However, if you happened to foresee such a situation, you could "save" the stdin descriptor, like this:

    int stdin_save;
    ...
    stdin_save = dup(0);
    ...
    close(0); // Here it is "impossible" to read input
    ...
    dup(stdin_save); // Possible to read input again!
    
  2. As explained by Eric Postpischil, if your stdout is connected to a file/device in a read-write way (as is typical with terminals), after doing dup(1), the normal read functionality is restored. But nothing unusual (like the program talking to itself) happens.

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222866

What it means is that you now have stdout open on file descriptor 0. Whether you can read from that file descriptor depends on what your stdout actually is. If your stdout is a terminal (or pseudo-terminal) that has both input and output capability, then you may be able to read it. If your stdout is a file that the shell that started your program opened in write-only mode, then you might not be able to read it.

In any case, you should not rely on any particular behavior; you should not expect to be able to read from file descriptor 0 after doing this.

Upvotes: 1

Related Questions