0

I have problem when I use csignal.

I use Visual Studio 2019

#include <Windows.h>
#include <csignal>
#include <iostream>

void signalHandler(int signum)
{
    std::cout << "Interrupt signal (" << signum << ") received.\n";


    exit(signum);

}

int main()
{

    std::signal(SIGINT, signalHandler);

    while (1)
    {
        std::cout << "Going to sleep...." << std::endl;
        Sleep(1);
        raise(0);
    }
    std::cout << "Hello World!\n";
    return 0;
}

when raise called after I had:

enter image description here

I have ucrtbased.dll in:

C:\Windows\System32

I installed Windows SDK. I don't understand what is wrong?

Nimantha
  • 6,405
  • 6
  • 28
  • 69
SMax23
  • 11
  • 2

1 Answers1

0

You're raising signal 0 (raise(0);) which is probably an invalid signal value.

You should use the standard #defines (which may have compiler-specific values) for parameter (see spec).

littleadv
  • 20,100
  • 2
  • 36
  • 50
  • Ok, it works.But now,when I delete `raise(0)` and after that start app again and presse `Ctrl+C` I had new problem: **Exception thrown at 0x00007FF9F0F93695 (KernelBase.dll) in ConsoleApplication2.exe: 0x40010005: Control-C.** why it not works now? – SMax23 Jan 08 '22 at 01:50
  • 1
    You should really read the spec, specifically the "Signal handler" part: https://en.cppreference.com/w/cpp/utility/program/signal . Read carefully which standard library calls you can safely make from it. Hint: it's not a lot. – littleadv Jan 08 '22 at 02:39
  • I see this code,but I have Exception,when presse Ctrl+C [https://www.tutorialspoint.com/how-do-i-catch-a-ctrlplusc-event-in-cplusplus](https://www.tutorialspoint.com/how-do-i-catch-a-ctrlplusc-event-in-cplusplus) – SMax23 Jan 08 '22 at 22:48
  • @SMax23 this code is a bad example. Using `cout` in the signal handler leads to undefined behavior. See the link I gave you in the previous comment. Not every piece of code you find online is perfect, just FYI – littleadv Jan 08 '22 at 23:15
  • @SMax23 You'll find the full list of library functions that are required to be singal-safe here: https://pubs.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_04 (scroll down a bit). The link in my first comments includes a link to this page. – littleadv Jan 08 '22 at 23:18
  • @SMax23 Also see this: https://stackoverflow.com/questions/16891019/how-to-avoid-using-printf-in-a-signal-handler – littleadv Jan 08 '22 at 23:21