简体   繁体   中英

Signal handling doesn't work with -ansi or with POSIX define

I'm trying to use the signal function (I know it's deprecated and there are a lot of problems with its portability but I can't use sigaction).

I also need to compile with -ansi and -D_POSIX_C_SOURCE=200112L

If I compile with one of these flags, signal only works one time. How can I get the same behavior with these flags without using sigaction please ?

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

    static void     signal_handler(int nbr)
    {
      (void)nbr;
      puts("\nHi ! ");
    }

    int              main(void)
    {
      signal(SIGINT, signal_handler);
      puts("Hi ! ");
      while (42);
      return (0);
    }

Be aware, the above code contains an infinite loop.

Thanks :)

Looks like your system has the Unix/System V signal mechanism, which resets the signal action to SIG_DFL after the first signal. So you have to reinstall the handler in the signal handler itself:

  static void     signal_handler(int nbr)
    {
      signal(SIGINT, signal_handler);
      (void)nbr;
      puts("\nHi ! ");
    }

From signal linux man:

       * On glibc 2 and later, if the _BSD_SOURCE feature test macro is not
         defined, then signal() provides System V semantics.  (The default
         implicit definition of _BSD_SOURCE is not provided if one invokes
         gcc(1) in one of its standard modes (-std=xxx or -ansi) or defines
         various other feature test macros such as _POSIX_SOURCE,
         _XOPEN_SOURCE, or _SVID_SOURCE; see feature_test_macros(7).)

I tried just at random and compiled with -D_BSD_SOURCE and on Ubuntu it works as intended.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM