C程序在被告知之前执行命令

Bl4*_*4z3 3 c printf command-execution

我已经开始研究使用C的命令处理,但我遇到了这个C程序的问题.它正在执行ls命令之前.

Gcc信息:

gcc version 6.2.1 20161124 (Debian 6.2.1-5)
Run Code Online (Sandbox Code Playgroud)

这是代码:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;

    printf("Is command processor available?\n");
    if (system(NULL))
    {
        printf("Command processor available!\n");
    }
    else
    {
        printf("Command processor not available!\n");
        exit(1);
    }

    printf("Executing command ls");
    i=system("ls");

    printf("Returned value is: %d.\n",i);
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

我所说的代码就是这条特定的代码:

    printf("Executing command: ls");
Run Code Online (Sandbox Code Playgroud)

如果使用该段代码运行程序,则输出为:

Is command processor available?
Command processor is available
systemProcessing  systemProcessing.c
Executing command: lsReturned value is: 0.
Run Code Online (Sandbox Code Playgroud)

它在实际被告知之前执行命令

但是当我使用新行"\n"完成代码时,其输出符合预期:

Is command processor available?
Command processor is available
Executing command: ls
systemProcessing  systemProcessing.c
Returned value is: 0.
Run Code Online (Sandbox Code Playgroud)

为什么将新行添加到字符串中,代码会在执行之前打印出它要执行的操作,但如果没有它,它会执行然后打印将要执行?

PSk*_*cik 7

这是一个缓冲问题.你需要这样做:

printf("Executing command ls");
fflush(stdout); //<<
i=system("ls");
Run Code Online (Sandbox Code Playgroud)

或者,如果您的输出是行缓冲终端,并且您可以添加行而不是显式fflush(stdout)调用:

printf("Executing command ls\n"); 
Run Code Online (Sandbox Code Playgroud)

stdio 101:

对OS的小读/写效率低,因此stdio IO(默认情况下)将每个文件句柄/描述符与输入缓冲区和输出缓冲区相关联.stdio输出调用输出到适当的FILE(在这种情况下,它的stdout)输出缓冲区(通过memcpy字符串),并且只有当(大)缓冲区已满时才会进行系统调用以写入整个缓冲区(问题已解决) .

可以使用该fflush()函数引出输出缓冲区的显式刷新.另外,如果stdio检测到输出FILE是终端,它将使用行缓冲,这意味着它将fflush()在输出中遇到换行符时调用.

stdio FILE 的缓冲模式也可以使用setvbuf()函数显式操作.请参阅链接中的联机帮助页以了解如何使用它.


tas*_*oor 6

标准输出via printf是缓冲的,这意味着它在调用后不会立即刷新到目的地printf.当您system在调用之后运行单独的进程printf而没有刷新时,可能会在打印之前打印新进程的输出printf.

添加新行会产生差异,因为新行会立即刷新缓冲区.您也可以使用fflush而不是换行符.