1

Possible Duplicate:
Are file descriptors shared when fork()ing?

Suppose I have following code in linux:

int main()
{
   FILE* f = fopen("file.txt", "w");
   fork();
   fwrite("A", 1, 1, f);
   fclose(f);
   return 0;
}

What I know about fork from documentation, is that it makes the copy of current process. It copies state of the memory as well, so *f should be equal in both instances. But what happens with system resources, such as a file handle? In this example I open the file with write intentions, so only one instance can write into file, right? Which of the instances will actually write into file? Who should care further about the file handle, and call fclose() ?

Community
  • 1
  • 1
Dmitry Bespalov
  • 5,179
  • 3
  • 26
  • 33

1 Answers1

1

Both processes get a handle. Both can write, but will share the current offset. Both should close, each closes its own handle.

glglgl
  • 89,107
  • 13
  • 149
  • 217
unbeli
  • 29,501
  • 5
  • 55
  • 57
  • unbeli, am I correct that if to call exec() after fork() (say in the child process), then all shared resources in child process will be correctly closed, as if the application was just terminated? – Dmitry Bespalov Jun 25 '12 at 07:40
  • @DmitryBespalov well, they won't be closed on exec() (unless you set FD_CLOEXEC), but they will be closed when the child terminates, of course. But that won't affect parent's handles, they will remain open until you close them or parent terminates. – unbeli Jun 25 '12 at 11:44