Signal handling in c++
im new in c++,i want to know when we need to use signal handling in our program?and i saw in some codes that they fork after setting up signal,what fork means here?
TIA
I strongly recommend the book Advanced Programming in the Unix Environment, 2nd Edition as your guide to systems programming.
fork(2)
spawns a new process; it is almost entirely a clone of the current process. But the differences are vast: the return value from fork(2)
is different in parent and child, the child has a new pid
, new ppid
, and all filedescriptors that had their FD_CLOEXEC
flag set will be closed in the child (see fcntl(2)
for details). There are other differences, but this is a good start.
When setting up signal handlers, the most important things to keep in mind: Use sigaction(2)
to install signal handlers, not signal(3)
. signal(3)
is unreliable and allows for losing signals. You can't do much. The list of allowed functions that you may call in a signal handler is in the signal(7)
manpage. Using functions outside this list is dangerous and can create some very difficult bugs. You can also set flags in your program that are checked by your main event loop, so you can cleanly exit or print status or reload config files at appropriate times.
Fork is a built-in function in C that causes the program to create a child instance of itself, which begins execution at the point fork was called. Shells fork before running a command, which is good because if the command causes a crash or freeze, the forked instance of the program can be killed while keeping the parent alive.
精彩评论