Weiheng Li
Weiheng Li

Reputation: 565

In C, printf() without newline doesn't generate output even with signals?

I am using the gcc of Mac right now. The program below runs well. Here I mean when I press control+c, terminal shows " now got a SIGINT signal\n":

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void handler(int s)
{
       if (s == SIGINT) printf(" now got a SIGINT signal\n");
}
int main()
{
        signal(SIGINT, handler);
loop:
/* spin here, waiting for ctrl-c */
          goto loop;
}

However, when I add one line, something strange happened:

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void handler(int s)
{
       if (s == SIGINT) printf(" now got a SIGINT signal\n");
}
int main()
{
printf("process id is %d ",getpid());
        signal(SIGINT, handler);
loop:
/* spin here, waiting for ctrl-c */
          goto loop;
}

The terminal doesn't show "process id is...", but after I press ^c, the terminal outputs ^Cprocess id is 13888 now got a SIGINT signal. This really confuses me. In fact, the output is really unusable; the function is a simplicity of code as below:

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
void sigroutine(int dunno) {
switch (dunno) {
case 1:
printf("Get a signal -- SIGHUP ");
break;
case 2:
printf("Get a signal -- SIGINT ");
break;
case 3:
printf("Get a signal -- SIGQUIT ");
break;
}
return;
}
int main() {
printf("process id is %d ",getpid());
signal(SIGHUP, sigroutine); 
signal(SIGINT, sigroutine);
signal(SIGQUIT, sigroutine);
for (;;) ;
}

Its output on my terminal seems to be nothing. Whatever I input, it never response. I begin to delete sentence one by one, and replace switch with if, replace for with goto and delete the getpid(). Finally, I don't why it can respond to control+c. However the behavior of getpid() is really weird to me. Could you explain to me about this?

I also tried only output getpid() without signal(). It works well.

BTW: how can I rerun the program without opening another terminal since Ctrl+c is useless.

Upvotes: 1

Views: 4067

Answers (2)

Suraiya Khan
Suraiya Khan

Reputation: 102

For first part of your concern - in main method please replace

printf("process id is %d ",getpid());

with

printf("process id is %d\n",getpid());

Here is the reason: Why does printf not flush after the call unless a newline is in the format string?

Printf ideally buffers characters - with \n or newline we are instructing it to flush (it is finally printing instead of accumulating/buffering what to print) ... please note that the printf inside your handler has a new line ... that explains why you were seeing the pid after hitting CTRL+C.

Upvotes: 2

John3136
John3136

Reputation: 29266

The output from the first printf is buffered. Either add a \n, or use fflush() to force the buffer to be flushed.

See here for more description: Why does printf not flush after the call unless a newline is in the format string?

Upvotes: 4

Related Questions