Link to home
Start Free TrialLog in
Avatar of sobhan102398
sobhan102398

asked on

signal trapping in linux

Consider the following code
void alter();
main()
{
int i;
signal(SIGINT,alter);
for(i=0;i<1000;i++)
printf("Uninterrupted\n");
}
void alter()
{
printf("Interrupted");
sleep(2);
}
When I try to beak using Ctrl+C it does not go into the alter sub function.
However if use a sleep function within the for loop it connects to the alter sub function.
How can I make the SIGINT signal to be trapped in the first case.
Avatar of sobhan102398
sobhan102398

ASKER

I tried it again today.
I observed it closely and this is what i got,
When I press Ctrl + C the signal is being generated but very late and printf("Interrupted) print's so fast that is difficult to track. I used the following
void alter()
{
printf("Interrupted\n");
sleep(2);
}
The sleep doesn't work and printf statement is executed like as I have stated above.

Also when I try out this for the signal signal(SIGPWR,alter1);
void alter()
{
create("file",0700);
exit(1);
}
I switch off the computer and when I on it again the file is not created i.e SIGPWR is not trapped.Why is it so.

One last question regd signal trapping
can i trap the signal for the following code
while((no=read(f,buff,1024))>0)
write(f1,buff,no);
I used sleep(1) like this
while((no=read(f,buff,1024))>0)
{
write(f1,buff,no);
sleep(1);
}
Now I was able to trap it.
How can I trap the signal in the first case without using sleep.
Is read and write non blocking.
Avatar of ozo
What are you trying to do?
I'd expect
for(i=0;i<1000;i++) printf("Uninterrupted\n");
to run so fast that the ouput buffer is full before you can type a Ctrl+C
and even if you can type Ctrl+C fast enough, the buffer won't be flushed before the next "\n" is printed.
I am trying to copy one file to another. When I interrupt the process, I should save till that point by calling alter where I write some code for that. However I am unable to trap the signal SIGINT within this loop
while((no=read(f,buff,1024))>0)
      write(f1,buff,no);
I have to use sleep inorder to capture the signal.I want my program to trap the signal without using sleep
ASKER CERTIFIED SOLUTION
Avatar of rdelfino
rdelfino

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Also we connect from dos to linux using a ncsa rlogin program. Whenever we                     press Alt+a we get a new session . Or we press Alt+x we close the session.
                    i.e The program is written such that when a person presses Alt+a he goes to a particular function. So they are trapping keys at any point.
                    How can I simulate this.
I need to go to a particular function from whatever state I am when I press a selected  hot key. Using this I can bypass the above problem(printf pob) by using another set of keys
other than Ctlr+C.
How do I do this