systemasis systemasis - 1 year ago 79
C Question

Close file after a kill command

I have an infinite loop in my program where it will write in a file defined as stdout until I kill it. Therefore, the file will never be closed and won't contain what was wrote.

Is there a way to close the file after a kill command ?

I could use signals, like

signal(SIGTERM, close(filename));

but how would I handle all the kill signals ?

Art Art
Answer Source

Your question is tagged with "linux", so unless you buffer your writes and don't flush the buffer (e.g. when using fwrite you need to call fflush sometimes), the contents will be written to the file because it will be properly closed on exit (even if the exit is forced by a signal). You don't need fsync unless you're doing something that has to survive a machine crash (and then you need to know what you're doing to get crash semantics right).

Since you mentioned close in what you want to do in the signal handler, it doesn't seem you're buffering your writes, so you don't need to do anything. Data written with successful calls to write will end up in the file unless your machine crashes (or your disk/filesystems break before flushing the buffer cache, don't worry about that). In fact, the moment write returns in your program, the data can be considered written into the file and will be visible by other processes that read that file (an exception to this is if the machine crashes or a few filesystem edge cases, but that's a much more complex topic).

If all you do in your signal handlers is to close your file descriptors and _exit then you don't need the signal handlers.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download