Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

c - Why no output on console on signal handling?

I was trying this program from Advance Programming in Unix Environment.

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

static void handler(int sig){
    if(sig == SIGUSR1)
        printf("handled user1 signal");
    else if(sig == SIGUSR2)
        printf("handles user2 signal");
    else
        printf("unkown signal");
}

int main(){

    if(signal(SIGUSR1, handler) == SIG_ERR)
        printf("can't handle signal SIGUSR1");
    if(signal(SIGUSR2, handler) == SIG_ERR)
        printf("can't handle signal SIGUSR2");
    for(;;)
        pause();
    return 0;
}

I am using Ubuntu 11.10. I compile the program with gcc and then run a.out as indicated in the book.

$./a.out& [1]+ 1345

$ kill -USR1 1345

But there is no output printed. The program keeps running in backgound and I have to kill it.

Other things I have tried:

  1. Tried handling SIGINT to see if running program in background is causing problems. Still no output.

  2. Downloaded latest release of FreeBSD and tried the same program on it, but with same problem.

  3. I put a printf statement before setting signal handler:

    int main(){
        printf("printf is working...");
        //exit(0);
        if(signal(SIGUSR1, handler) == SIG_ERR)
        ...
    

when exit() is commented, there is no output. When I uncomment it, the output is printed.

Please tell me what am I doing wrong in this?

PS: Don't suggest using sigaction(). I am learning Unix Programming, not building any practical application.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The output from printf is buffered. That means it's stored in memory until flushed to the output. The best way to flush text in printf is to end the text with a newline. You can also flush manually with the fflush function.

However, you should be cautioned that using output functions like printf and fflush is not considered safe in signal handlers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...