Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
416 views
in Technique[技术] by (71.8m points)

c - Using a sigaction handler with sigaction when SA_SIGINFO is not set

The spec says that

If SA_SIGINFO is specified in sa_flags, then sa_sigaction (instead of sa_handler) specifies the signal-handling function for signum.

However, the following code works magically

#include <stdio.h>
#include <signal.h>

static void handler(int signo, siginfo_t *si, void *uc){
   printf("si = %d
", *(char*)si);
   printf("uc = %d
", *(char*)uc);
}

int main(void)
{
      struct sigaction psa;
      psa.sa_flags = 0;
      psa.sa_sigaction = handler;
      sigaction(SIGTSTP, &psa, NULL);
      for(;;) {}
      return 0;
}

handler is able to access memories at si and ui, and gdb shows that at least si is indeed a pointer to siginfo_t. However, the code implements sa_sigaction and sa_handler as a union. If the runtime uses sa_flags to decide to use sa_sigaction or sa_handler, it seems hard to know sa_sigaction should be used...

Does this mean the runtime always provides si and uc to both the two kinds of calls? Is such a user code well-defined?

question from:https://stackoverflow.com/questions/65838954/using-a-sigaction-handler-with-sigaction-when-sa-siginfo-is-not-set

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Does this mean the runtime always provides si and uc to both the two kinds of calls?

It means that particular implementation does, yes.

Is such a user code well-defined?

No, it means that it relies on undefined behavior that happens to work on one particular platform.

Note that, even on your present platform, this shortcut might not work for you. You could forgive your runtime for itself taking a shortcut with garbage in the siginfo_t and ucontext_t parameters. After all, by not omitting SA_SIGINFO, you told the implementation that you wouldn't need that information.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...