2

For example, if I use kill (a function in C library signal.h) to emit a SIGINT signal to a child, will the SIGCHLD signal from the child be caught before the kill function returns?

Rossil
  • 67
  • 5

3 Answers3

4

While the kill syscall isn't interruptible (at least according to the man page), there's still at least two cases in which the SIGCHLD handler could run before the function returns:

  1. If there's another thread in your process, the kernel could choose to run the signal handler there even before the kill syscall returns in your first thread.
  2. You're probably using a wrapper function for kill from your libc. The signal handler could run in between the syscall returning to it, and it returning to your code.

So if you want to make sure you don't get the SIGCHLD until after kill returns, then you need to use sigprocmask to block it before the kill until you're ready for it.

  • 3
    Even if you call kill "directly" with an inline asm instrution (syscall or int or whatever your target uses), the signal handler might run before the instruction after that. So while this is technically after the system call returns, it is not usefully so. – Chris Dodd May 03 '20 at 18:57
  • 3
    @ChrisDodd Technically correct is the best kind of correct :) But on a serious note, the solution to OP's (vague) problem is still "block it with `sigprocmask` until you're ready for it". – Joseph Sible-Reinstate Monica May 03 '20 at 19:01
  • Thanks for your help. When I say the interruption, I mean the SIGCHLD signal exactly emitted by the child that is terminated by the kill function. I neglect that kill is a syscall so all the signals will be blocked before the program returns to the user mode. But I’m still confused with Chris Dodd’s comment. Can I say that before kill function returns, it should return from kernel to user mode, and the period when it remains at user mode before returning is when it will be interrupted by the signal? – Rossil May 06 '20 at 12:13
  • @Rossil Your process's thread that issued the `kill` will not be interrupted by the signal while it's still in kernel mode. – Joseph Sible-Reinstate Monica May 06 '20 at 14:02
2

I don't know if this answers your question but, reading the Linux man page, the possible return values of kill are EINVAL, EPERM, and ESRCH. EINTR is not one of them. That makes me think that the function won't be interrupted. At least, the system call won't be interrupted.

EDIT: I mean errno, not return, values.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
2

Signal handling is asynchronous. There is therefore no guarantee either way about whether the SIGCHLD emitted when the child terminates will be received by the parent before the kill call returns. My guess would be that kill will usually win the race and return before the SIGCHLD arrives, but it is not safe to depend on that.

John Bollinger
  • 160,171
  • 8
  • 81
  • 157