What is the best way to allocate memory when signals are handle?

I know malloc is not a safe function, so I will be happy if you give me a correct and standard way to allocate memory when signals are handle. For example, let's say I would like to store in a linked list the time each child process terminates. How can I create new nodes for the linked list without using malloc inside a signal handler? I am very new with this topic.



answered 5 days ago Whilom Chime #1

You can't allocate memory in a signal handler; you have to have allocated the memory before you register the signal handler. Before you register your signal handler you might allocate an array of structs to record information in while in the handler, but you have to make sure you allocate enough!

answered 5 days ago R.. #2

While not directly an answer to your question as written, the right answe is basically: don't. Don't do anything in the signal handler. Don't even install a signal handler if you don't have to.

For your example with child processes, your SIGCHLD handler should do nothing more than wake up another part of the program (e.g. with the self-pipe trick) to wait on the child process that exited and record its status. Even better, just make a thread for each child process you're waiting on to perform a synchronous waitpid; then no global state or signal handler is needed.

comments powered by Disqus