i'd like to know if it is necessary (or advisable) to unmap shared memory (using munmap) in child created via fork, if the memory was obtained in the parent, before the fork, using mmap(..., MAP_ANONYMOUS | MAP_SHARED,...) and will also be unmapped in the parent, which will wait for the child.
Also i would like to know whether it is necessary (or advisable) to close a file in the child, if the file was opened in the parent (before the fork, using fopen) and will be closed in the parent after the child terminates.
I am thinking of using a user-defined signal and a signal handler in which the parent will wait for child processes, and then the process -- wheter it is the parent or not -- will close the file and unmap the memory. This signal will be sent to all processes in the group from a process, in which an error occurred (i do not want to pass return values).
Actually it is a bit more complex, but i only want to know whether i need to do this:
void sig_handler() {
if (getpid() == getpgrp()) // parent
while (proc_count--)
wait(NULL); // signal has already been sent to all child processes
// every single process will do this:
fclose(memory->file);
munmap(memory, size);
exit(123);
}
or it is completely OK to do this:
void sig_handler() {
if (getpid() == getpgrp()) {
while (proc_count--)
wait(NULL);
fclose(memory->file);
munmap(memory, size);
}
exit(123);
}
I have tried closing the file in one child process; it seemed to have no effect in other processes -- i assume the fd table is copied on fork. Is there a way to make it shared between processes? (Probably not, i suspect)
Any answer is appreciated. Thank you.
PS. Is there a reason why can't i start my question with a greeting (eg. Hello) ?
If you're going to exit the process, there's no point in calling munmap(). The memory will be unmapped for that process when the process exits.
fclose() will flush any buffers holding unwritten data to the file. In all processes - the parent and the child. Whether or not you want that is up to you.
exit() implicitly flushes all buffers. _exit() does not flush buffers or call any other exit handlers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With