The calling system () of c

I tried to make system calls c. When the following code is executed, the date is printed first, and then " Todays date is ..........:" in a new line. When I replaced printf with puts, it did as I expected. ( objdump showed puts @plt instead of the second printf ). Can someone tell me why this 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.

+4
source share
4 answers

printf() put your line in the buffer, and as soon as you go down the line, it will write it to the screen. why when do you

 printf(" Todays date is ..........:"); system("/bin/date"); 

You can print the date first.

The stdout stream is buffered, so it will only show what is in the buffer after it reaches a new line (or when it was said). You have several print options at once:

  • Type stderr instead of fprintf :

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

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

     setbuf(stdout, NULL); 
+5
source
 printf(" Todays date is ..........:"); 

==>

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

Or add fflush(stdout); after the line printf ;

+3
source

printf use a buffer.
If you want to print text immediately, you must call fflush

 printf(" Todays date is ..........:"); fflush(stdout); system("/bin/date"); 
+2
source
  #include <stdlib.h> #include <stdio.h> int main() { printf(" Todays date is ..........:\n"); //add \n at the end. this is same behavior as puts. now date will print after this system("/bin/date"); printf("\n This is your exclusive shell\n"); system("/bin/sh"); return 0; } 

otherwise you can use fflush(stdout); after printf("Todays date is ....:"); statement

+1
source

Source: https://habr.com/ru/post/1497978/


All Articles