为什么在这里调用 printf 会无限打印消息?

问题描述 投票:0回答:0

目标是阻塞线程,直到新数据写入文件。我正在使用

read()
来做到这一点。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>

void sigint_handler(int sig) {
    printf("received SINT, exiting gracefully, com mto carinho...\n");
    exit(0);
}

int main() {

    signal(SIGINT, sigint_handler);

    char buffer[256] = { 0 };
    int fd = open("foo.txt", O_RDONLY);
    
    if(fd == -1) {
        printf("error opening file\n");
        return -1;
    }

    while(1) {
        
        ssize_t nbytes = read(fd, buffer, sizeof(buffer));

        if(nbytes == -1) {
            printf("error reading file\n");
            close(fd);
            return 1;
        }
        
        //printf("new data: ");
        printf("%.*s", (int) nbytes, buffer);

    }

    close(fd);
    return 0;
}

现在如果我调用

printf("new data: )
它会无限地打印“新数据:”但是如果我省略它并且只留下
printf("%.*s", (int) nbytes, buffer);
它打印从 read() 读取的内容然后阻塞当前线程......是什么导致了那个我该如何解决?

c linux file-read
© www.soinside.com 2019 - 2024. All rights reserved.