开发者

Standard Buffer not getting cleared before system() call

#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??


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/


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

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


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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜