从c调用system()

时间:2013-08-20 11:09:25

标签: c system

我试图从c执行系统调用。执行以下代码时,首先打印日期,然后在新行上打印" Todays date is ..........:"。当我用puts替换printf时,它按照我的意图执行。(objdump显示 put @ plt 代替第二个printf)。谁能告诉我为什么会这样?

  #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; 
    }

提前致谢。

4 个答案:

答案 0 :(得分:4)

printf()将你的字符串放在缓冲区中,一旦你走了一行,就把它写到屏幕上。这就是你做什么的原因

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

system("/bin/date");

您可能会先打印日期。

stdout流被缓冲,因此只会在到达换行符后(或者告诉它时)显示缓冲区中的内容。您可以选择立即打印:

  • 使用stderr打印到fprintf

    fprintf(stderr, "I will be printed immediately");
    
  • 只要您需要使用stdout

    ,请点击fflush
    printf("Buffered, will be flushed");
    fflush(stdout); // Will now print everything in the stdout buffer
    
  • 或者您也可以使用stdoutsetbuf上停用缓冲:

    setbuf(stdout, NULL);
    

答案 1 :(得分:3)

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

==&GT;

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

或在fflush(stdout);行之后添加printf;

答案 2 :(得分:2)

printf使用缓冲区 如果您想立即打印文本,则必须致电fflush

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

答案 3 :(得分:1)

  #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; 
    }  

或者您可以在fflush(stdout);声明

之后使用printf("Todays date is ....:");