Joseph
Joseph

Reputation: 13178

C: close(2) after fork()?

Quick question, hoping someone can verify. After a fork, if you call close(2) in the parent, stderr in the child is unaffected. However, if you call close(2) in the child, stderr in the parent is closed. Does that seem right? I tested this in FreeBSD and it seems to be the case, but I'm not sure why. I would expect that either they both don't affect each other or they do, but not this.

Any insight?

Upvotes: 1

Views: 1298

Answers (1)

Diego Sevilla
Diego Sevilla

Reputation: 29001

After a fork, every open file descriptor in the parent gets dup'ed, so any close after the fork won't affect either the parent or the child.

Unless, you're doing it not properly (i.e. not checking the output of the fork() system call).

Upvotes: 6

Related Questions