You are not logged in.

#1 2016-07-12 01:22:34

leetow2006
Member
Registered: 2013-02-13
Posts: 21

How to interrupt by signal?

I am sorry,my English is very poor.
I want that the function read is interrupted by alarm signal without input
from stdin,but my code isn't interrupted,it is only output "recv a sig"
and then wait.How to correct?thank you very much.
Look:
<b>
void handler(int sig)
{
        printf("recv a sig=%d\n",sig);
}
int main()
{
        signal(SIGALAM,handler);
        alarm(3);
        char buf[1024];
        int ret;
        ret=read(0,buf,sizeof(buf));
        if(ret==-1)
        {
                printf("interrupt by alarm signal\n");
        }
        return 0;
       
}
</b>

Offline

#2 2016-07-12 02:05:49

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,529
Website

Re: How to interrupt by signal?

Is this on archlinux?

This would highlight one of the reasons why the man page of signal suggests it should not be used.  You should use sigaction:

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


void handler(int sig) { printf("recv a sig=%d\n",sig); }

int main() {
	struct sigaction sa;
	sa.sa_handler = handler;
	sigemptyset(&sa.sa_mask);
	sa.sa_flags = 0;
	sigaction(SIGALRM, &sa, NULL);
	alarm(3);
	char buf[1024];
	int ret;
	ret=read(0,buf,sizeof(buf));
	if(ret==-1) printf("interrupt by alarm signal\n");
	return 0;
}

EDIT: I see you were told in your previous thread (on what looks like an identical question) to use code tags.  Is there a reason you have not used code tags?  Is there a reason you abandonded your other thread?  These - along with the question about which distro you are on - are not optional questions: please address them or your posts will be removed.


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

Board footer

Powered by FluxBB