Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

calling system() from c

Tags:

c

system

I was trying to execute system calls from c. When the following code is executed, the date is printed first followed by " Todays date is ..........:" on a new line. When I replaced printf by puts, it executed as I intended.(the objdump showed puts@plt in place of the second printf). Can anybody tell me why it is so?

  #include <stdlib.h>

    int main() { printf(" Todays date is ..........:");

    system("/bin/date");
    printf("\n This is your exclusive shell\n");  
    system("/bin/sh");
    return 0; 
    }

Thanks in advance.

like image 238
user146297 Avatar asked Aug 13 '26 16:08

user146297


1 Answers

The printf() put your string in a buffer, and once you go down a line it write it to the screen. that's why when you do

printf(" Todays date is ..........:");

system("/bin/date");

You might get the date printed first.

The stdout stream is buffered, so will only display what's in the buffer after it reaches a newline (or when it's told to). You have a few options to print immediately:

  • Print to stderr instead using fprintf:

    fprintf(stderr, "I will be printed immediately");
    
  • Flush stdout whenever you need it to using fflush:

    printf("Buffered, will be flushed");
    fflush(stdout); // Will now print everything in the stdout buffer
    
  • or you can also disable buffering on stdout by using setbuf:

    setbuf(stdout, NULL);
    
like image 156
No Idea For Name Avatar answered Aug 16 '26 20:08

No Idea For Name



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!