I have to interrupt a read call if ctrl-c is pressed, using signal. I wrote this (simplified) sample code:
#include <unistd.h>
#include <sys/wait.h>
int should_stop = 0;
void sighandler(int signal)
{
write(1, "\nctrl-c has been pressed\n", 25);
should_stop = 1;
}
void read_function()
{
char c;
while (!should_stop)
read(0, &c, 1);
//Do some stuff and return someting
}
int main()
{
signal(SIGINT, &sighandler);
read_function();
write(1, "read_function is over\n", 22);
return (0);
}
As read is a blocking call (as far as I understood), the should_stop global variable will not be evaluated once read has been called. So I don't know how I could interrupt the read call by pressing ctrl-c.
Another constraint is that I'm only allowed to use those functions:
- write
- read
- fork
- wait
- signal
- kill
- exit
So I can't use select to set a timeout value. As I also need the return value of read_function, I can't use fork and just exit the process with a different signal handler.
Is there another way to interrupt the read call?