c - 除非在使用输出重定向时调用显式 fflush 函数,否则线程不会给出输出

标签 c linux multithreading unix io-redirection

我正在编写一个多线程程序。程序结构如下所示

int main()
{

    printf("To Call threads\n");
    thread1=pthread_create(&trd1,NULL,process1,(void *)sleepTimeForP1);
    thread2=pthread_create(&trd2,NULL,process2,(void *)sleepTimeForP2);
    pthread_join(trd1, NULL);
    pthread_join(trd2, NULL);
    return 0;
}

线程的代码是

void *process1 (void *sleepTimeForP1)
{
    int *tsleepTimeForP1 = (int *)sleepTimeForP1;
    while(1)
    {
        pthread_mutex_lock(&lock);
        printf("inside thread\n");
        pthread_mutex_unlock(&lock);
        sleep(1);
    }

}

该代码工作正常,并在未完成输出重定向时打印输出。但是当给出输出重定向时,文件中没有输出。现在,如果我在每个 printf() 语句之后给出显式 fflush(stdout),我就会得到所需的输出。为什么我需要给出明确的 fflush() ?

最佳答案

来自 C99 §7.19.3[7]:

As initially opened, the standard error stream is not fully buffered; the standard input and standard output streams are fully buffered if and only if the stream can be determined not to refer to an interactive device.

“完全缓冲”(相对于“行缓冲”):C99 §7.19.3[3]

When a stream is fully buffered, characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a stream is line buffered, characters are intended to be transmitted to or from the host environment as a block when a new-line character is encountered.

因此,当标准输出是交互式的(例如 shell)时,它是行缓冲的。但是,当您将它重定向到一个文件时,它会变成完全缓冲的,您必须使用 fflush

关于c - 除非在使用输出重定向时调用显式 fflush 函数,否则线程不会给出输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32071041/

相关文章:

java - wait() 没有捕获 notification();导致奇怪的死锁行为

c - Makefile:没有链接问题的编译

linux - 如何使用 bash 在空文件的某些行上存储特定数据

c - 我试图通过 ioctl 从驱动程序获得的以太网速度是恒定的,比如 57872Mbps,为什么?

linux - find 命令搜索模式

linux - 循环附加到 tar 文件

java - 在多线程系统中使用静态 java.sql.Connection 实例是否安全?

c++ - 静态无功能线程安全吗?

c++ - 为什么优化会杀死这个功能?

c - 使用 C 语言制作 GUI 时如何避免使用控制台?