tags:

views:

43

answers:

3
#include<stdio.h>
#include<signal.h>
#include<stdlib.h>
void handler(int signo)
{
    printf("First statement");
    system("date");
    exit(EXIT_SUCCESS);
}

int main()
{
    signal(SIGINT,handler);
    printf("Waiting for KeyboardInterrupt\n");
    for(;;);
    return 0;
}

Test run:-

shadyabhi@shadyabhi-desktop:~/c$ gcc main.c
shadyabhi@shadyabhi-desktop:~/c$ ./a.out
Waiting for KeyboardInterrupt
^CWed Mar 10 23:55:47 IST 2010
First statementshadyabhi@shadyabhi-desktop:~/c$

Why is "First Statement" getting printed after system() call??

+2  A: 

Did you try flushing the buffer before calling system("date")?

I just added fflush(NULL); before system, and the output is as expected.

rmk
Ya. I know this.. But, still I got the right solution from @Mike..
shadyabhi
`fflush(NULL)` flushes *ALL* buffers, so it does not matter who has which buffer. fflush with a specific argument flushes only that buffer.
rmk
+1  A: 

The C IO API buffers things up in order to print more efficiently. Typically the buffer is flushed whenever you write out a newline or manually flush it.

So you can use a newline to flush the buffer:

printf("First statement\n");

Or use the fflush function:

printf("First statement");
fflush (stdout);
Dan Olson
Adding the "\n" will not always (for example if stdout is redirected to a file). `fflush` will.
Andrew Stein
Actually, I new that this happens.. But, as said my @Mike, I came to know that STDOUT is not being flushed bcos "date" command has another STDOUT stream..
shadyabhi
+2  A: 

The standard input, output and error streams are created when your process starts, which in this case is your C program. When you make the system call, another process is created to execute the date command, and it gets its own set of streams.

In your program, the printf output is buffered to the standard output stream of your C program. Then the output of date is buffered to its own standard output stream. When the system call ends, the date standard output stream is flushed, so you see the output. Then, when your C program ends, its standard output stream is flushed and you see the printf output.

You might find this fellow's posting helpful: http://www.pixelbeat.org/programming/stdio_buffering/

Mike Pelley
thats what i wanted.. :)
shadyabhi