C程序在被告知

时间:2017-02-04 07:57:06

标签: c printf command-execution

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

Gcc信息:

gcc version 6.2.1 20161124 (Debian 6.2.1-5)

这是代码:

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

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

    printf("Executing command: ls");

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

Is command processor available?
Command processor is available
systemProcessing  systemProcessing.c
Executing command: lsReturned value is: 0.

它在实际被告知

之前执行命令

但是当我使用新行&#39; \ n&#39;关闭代码时,其输出符合预期:

Is command processor available?
Command processor is available
Executing command: ls
systemProcessing  systemProcessing.c
Returned value is: 0.

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

2 个答案:

答案 0 :(得分:7)

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

printf("Executing command ls");
fflush(stdout); //<<
i=system("ls");

或者,如果您的输出是行缓冲终端并且您没问题 添加一行代替明确的fflush(stdout)调用:

printf("Executing command ls\n"); 

stdio 101:

对OS的小读/写效率低,因此 stdio IO(默认情况下)将每个文件句柄/描述符与输入缓冲区和输出缓冲区相关联。 stdio 输出调用输出到相应的FILE(在这种情况下,它是 stdout )输出缓冲区(通过memcpy字符串),并且仅在(大) )buffer is full将系统调用写入整个缓冲区(问题解决)。

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

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

答案 1 :(得分:6)

通过printf的标准输出被缓冲,这意味着它在调用printf后不会立即刷新到目的地。如果您在调用system之后使用printf运行单独的流程而没有刷新,则可能会在printf打印之前打印新流程的输出。

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