Sirona
Sirona

Reputation: 23

Cand you use a file descriptor if you copy it woth dup2() and the close it?

So i'm trying to use fork to redirect the output to the file specified in the command. First I pipe and then i copy the file descriptor of the file given to me in the place of stdout with dup2() like dup2(output_fd,1) and then i close output_fd. close(output_fd). Would the process still send the output to that file since I have closed it?

Upvotes: 0

Views: 113

Answers (1)

Atharva
Atharva

Reputation: 53

When you do

dup2(output_fd, 1);

It makes STDOUT point to the handle pointed by output_fd. So, at this stage there are two ways you can write to the stream pointed by output_fd.

Now when you do

close(output_fd);

It'll close output_fd but NOT STDOUT. So, even if you close output_fd you'll still be able to write to the pipe!

Upvotes: 0

Related Questions