Interrupt in C++ - c++

I am trying to understand interrupts and am looking for a simple code that uses interrupts. Could somebody please help me with it?

Here are two examples using the alarm function. alarm causes SIGALRM to happen n seconds after you call that function.
This program will run for 3 seconds, and then die with SIGALRM.
#include <signal.h>
#include <unistd.h>
int main() {
alarm(3);
while(true);
}
In this case, we'd like to catch SIGALRM, and die gracefully with a message:
#include <signal.h>
#include <unistd.h>
#include <iostream>
volatile bool alarmed = false;
void alrm_handler(int) {
alarmed = true;
}
int main() {
signal(SIGALRM, alrm_handler);
alarm(3);
while(not alarmed);
std::cout << "done" << std::endl;
}

Related

POSIX C/C++ sleep() and usleep() not working? (Raspberry PI)

I wrote a small programm on my RasPI and have trouble with the sleep() and usleep() functions. both of them don't work. When I use usleep() with a number below 1000000 (below 1 second) it works, whenever i try to use a number that should let the program sleep for 1 second or more, it doesn't work. I've been working on making the Digital pin HIGH for a given time.
I've tried to shrink the program to printf() and to sleep only:
#include <stdio.h>
#include <unistd.h>
int main()
{
while (true)
{
sleep(1);
printf("%.2f", 10.1);
}
}
works after flushing the output buffer
#include <stdio.h>
#include <unistd.h>
#include <chrono>
#include <thread>
int main()
{
while (true)
{
std::this_thread::sleep_for(std::chrono::seconds(1));
printf("%.2f\n", 10.1);
}
}

Linux c++: Will blocked threads prevent app process terminating after returning from main function?

This problem is duplicate, but I am still confused about how os will resolve child threads after returning from main function.
Most pepole said that os will invoke exit_group() or exit() to terminate all child threads.
However, I found blocked threads will prevent process terminating.Reading up the documention of linux man page, I didn't find the special works for blocked threads.
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>
using namespace std;
mutex m;
condition_variable cv;
int main() {
auto t = thread([]() {
unique_lock<mutex> lock(m);
cv.wait(lock);
});
t.detach();
sleep(1);
cout << "hello" << endl;
return 0;
}
Running above code will print "hello" and then always stuck in blocking.
If simulate the behaviors os to do, directly invoke _exit(2) (be equivalent to exit_group()) in main function, process will terminate normally.
#include <atomic>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>
using namespace std;
mutex m;
condition_variable cv;
int main() {
auto t = thread([]() {
unique_lock<mutex> lock(m);
cv.wait(lock);
});
t.detach();
sleep(1);
cout << "hello" << endl;
exit(0);
return 0;
}
If use exit() instead of _exit(2), process will be stuck after printing "hello".
So what exactly did os do after returning for main funcion? Will blocked threads prevent process terminating?
The following code will work normally.
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <thread>
#include <unistd.h>
using namespace std;
mutex m;
condition_variable cv;
int main() {
auto t = thread([]() {
unique_lock<mutex> lock(m);
cv.wait(lock);
});
t.detach();
auto t2 = thread([](){
unique_lock<mutex> lock(m);
cv.wait_for(lock,chrono::seconds(2));
cv.notify_all();
});
t2.detach();
sleep(1);
cout << "hello" << endl;
return 0;
}

C++ killing child thread stops execution of the main thread

I am completely confused with timers and how threads (pthread) work in C++
Timers arent timers but clocks and you cant (I at least cant) kill a thread without killing main thread.
What I need - a bit of code which executes once in 24hrs on a separate thread.
However if the app needs to stop it - I cant do anything but send SIGKILL to it (because join will wait till midnight). Once I kill that thread the app (main thread) seems to kill itself also.
I am open to suggestions.
On condition - I cannot use std::threads and I dont want to wake this thread more than once a day
But easiest for me would be to kill a child thread without stopping execution of the main thread (why this is the case anyway??)
Here is the sample:
#include <stdlib.h>
#include <string.h>
#include <iostream>
#include <stdio.h>
#include <unistd.h>
#include <thread>
#include <pthread.h>
#include <signal.h>
using namespace std;
void* Logger(void* arg) {
int* thread_state = (int*)arg;
cout << "Logger started" << endl;
sleep(24 * 60 * 60);
cout << "Logger thread exiting" << endl;
pthread_exit(0);
}
int main()
{
int thread_state = 0;
pthread_t logger_t;
int rc = pthread_create(&logger_t, NULL, Logger, (void*)&thread_state);
sleep(2);
//thread_state = 1;
pthread_kill(logger_t, SIGKILL);
cout << "i wuz here" << endl;
return 0;
}
output:
Logger started
Killed
I dont know how I missed it but if I call pthread_cancel instead of pthread_kill it works just fine.

Threads exiting prematurely

I have the following piece of code, meant to create two threads and execute them indefinitely. But when run, it exits after some iterations.
#include <iostream>
#include "error.h"
#include <cstdlib>
#include <pthread.h>
#include <string>
#include <time.h>
#include <sys/wait.h>
using namespace std;
#define NUM_THREADS 2
#define TIME_OUT 3
void *GoBackN(void* arg) {
while(true) cout<<"Thread executing"<<endl;
}
int main()
{
pthread_t t[NUM_THREADS];
pthread_create((&t[0]),NULL,&GoBackN,NULL);
pthread_create((&t[1]),NULL,&GoBackN,NULL);
wait(NULL);
return 0;
}
Output -
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Thread executing
Process returned 0;
I'm compiling on g++, and running a linux machine.
You have three threads and you allow the main thread to exit.
#include <iostream>
#include "error.h"
#include <cstdlib>
#include <pthread.h>
#include <string>
#include <time.h>
#include <sys/wait.h>
using namespace std;
#define NUM_THREADS 2
#define TIME_OUT 3
void* GoBackN(void* arg) {
while(true) cout<<"Thread executing"<<endl;
}
int main() // main thread starts here
{
pthread_t t[NUM_THREADS];
pthread_create((&t[0]),NULL,&GoBackN,NULL); // second thread starts here
pthread_create((&t[1]),NULL,&GoBackN,NULL); // third thread starts here
wait(NULL); // doesn't wait for very long (zero time)
// ...
// main thread keeps running here...
// ...
return 0; // whoops main thread ends closing program
}
You could put an infinite loop (or an infinite wait) in the main thread to stop it exiting the program.
int main()
{
pthread_t t[NUM_THREADS];
pthread_create((&t[0]),NULL,&GoBackN,NULL);
pthread_create((&t[1]),NULL,&GoBackN,NULL);
wait(NULL); // doesn't wait for very long (zero time)
// ...
// loop in the main thread too
while(true) cout<<"Main thread executing"<<endl;
// ...
return 0; // now we don't get here
}
Or more typically join the threads waiting for them to exit:
int main() // main thread starts here
{
pthread_t t[NUM_THREADS];
pthread_create((&t[0]),NULL,&GoBackN,NULL); // second thread starts here
pthread_create((&t[1]),NULL,&GoBackN,NULL); // third thread starts here
wait(NULL); // doesn't wait for very long (zero time)
// ...
// join threads here
pthread_join(t[0], nullptr);
pthread_join(t[1], nullptr);
// ...
return 0; // we get here when other threads end
}
Now the main thread is suspended and does not consume any CPU time while the other threads are running.
If you are using a modern compiler with C++11 support you can use the Standard Library threads something like this:
#include <thread>
#include <chrono>
#include <vector>
#include <sstream>
#include <iostream>
const int number_of_threads = 5;
// nasty little MACRO to provide synchronized output (crude but works)
#define SYNC_OUT(m) do{std::ostringstream o; o << m << '\n'; std::cout << o.str();}while(0)
void GoBackN(int id) {
while(true)
{
SYNC_OUT("Thread: " << id << " executing");
std::this_thread::sleep_for(std::chrono::milliseconds(500));
}
}
int main() // main thread starts here
{
std::vector<std::thread> threads;
for(int i = 0; i < number_of_threads; ++i)
threads.emplace_back(GoBackN, i); // start new thread
// ...
// join threads here
for(auto&& thread: threads)
thread.join();
}
I'd recommend using <thread> or <future>s std::async. After you create threads, you should either .join() them later or .detach() them, whereas .join() halts the main programs execution and .detach() does not.
#include <thread>
#include <iostream>
void foo()
{
std::cout << "print from thread" << std::endl;
}
int main()
{
std::cout << "before the thread starts" << std::endl;
std::thread t(foo);
t.join();
std::cout << "after thread finishes" << std::endl;
}
For more information you really should check out this for example.

Signal handling per process on Windows

In my C++ app I need to catch signal SIGSEGV, so on Linux it's easy, but on Windows I have a problem: signal from another thread didn't catch by handler.
#include <signal.h>
#include <iostream>
#include <thread>
void setPosixSignalHandler() {
signal(SIGSEGV, [&](int sig) {
std::cout << "Received SIGSEGV" << std::endl;
exit(EXIT_FAILURE);
});
}
void f() {
raise(SIGSEGV);
}
int main() {
setPosixSignalHandler();
std::thread t(f);
t.join();
return 0;
}
If I remove multithreading than it's working like a charm.
Is it possible to set a single handler for all threads?
I'm using MinGW64.