为什么C打印输出较晚?

时间:2015-03-31 00:47:11

标签: c linux raspberry-pi

我目前在Raspberry Pi计算机上运行一段C代码。它是一个随机数发生器,从连接到GPIO数字输入18的Geiger计数器读取。它产生随机位(见代码)并以8组为单位打印位。此外,每隔30秒,它打印出当前观察到的辐射水平。代码似乎工作正常,除非辐射源被带走。随机数的生成速度较慢,但​​它似乎也会减慢其余任务的速度。在程序开头打印的消息在生成一个随机数之前不会显示。发生这种情况时,不显示任何数字,但添加了一个没有数字的换行符。即使在程序运行时,辐射水平似乎每30秒打印一次,但也会在下一个随机数上打印。为什么C以错误的顺序执行代码?

#include <wiringPi.h>//library for I/O
#include <stdlib.h>
int main(int argc, char *argv[])
{
    int lastRead;//if this is first time observing current pulse
    int pulseCount = 0;//number of total pulses from Geiger counter
    long timing[4] = {0,0,0,0};//values to compare to produce one bit
    int bits[8] = {0,0,0,0,0,0,0,0};//the newest number
    int bitCount = 0;//counts how many random bits have been made
    int i = 0;
    float startTime = 0;//start of the clock
    float currentSec = 0;
    float currentMin = 0;
    float cpm = 0;
    long elapsedTime = 0;

    wiringPiSetupGpio();//establish physical connection
    pinMode(18, INPUT);//set pin 18 to be input
    printf("random\tradiation");

    while(1)
    {
        if( millis()-startTime >= 30000)//30 sec passed?
        {
            startTime = millis();
            currentSec = startTime/1000;
            currentMin = currentSec/60;
            cpm = pulseCount/currentMin;//calculate counts/min in several steps
            printf("\t%f", cpm);//output counts/min
        }
        if( digitalRead(18) == HIGH )//pin is reading high
        {
            if(lastRead==0)//is not reading the same pulse again
            {
                lastRead = 1;//pulse has been identified
                timing[pulseCount%4] = millis();//save the time
                pulseCount++;//pulse detected

                if( pulseCount%4 == 0 )//if times have been collected
                {
                    if( timing[1]-timing[0] > timing[3]-timing[2] )//make a random bit
                    {
                        bits[bitCount%8] = 0;//nth bit of set of 8 is 0
                    }
                    else {
                        bits[bitCount%8] = 1;//it is one
                    }
                    bitCount++;//note that a bit was added

                    if( bitCount%8 == 0 )//every 8 bits made
                    {
                        printf("\n");

                        for( i = 0; i < 8; i++)//print them on a new line
                        {
                            printf("%d", bits[i]);
                        }//for
                    }//if(bitCount%8==0)
                }//if(pulseCount%4==0)
            }//if(lastRead==0)
        }//if(digitalRead(18)==TRUE)
        else {
            lastRead = 0;//ready to read new pulse
        }//else
    }//while
}//main()

1 个答案:

答案 0 :(得分:9)

默认情况下,stdout上的输出在写入终端时会进行行缓冲。这意味着输出将保留在内存中,直到您打印换行符或调用fflush(stdout)(或输出缓冲区填满 - 通常为4K或8K字符)。

所以把fflush(stdout)放在你想要显示累积输出的地方。或者使用setbuf(stdout, NULL)完全禁用缓冲。