Weiheng Li Weiheng Li - 2 months ago 13
C Question

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.

Answer

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?

Comments