gpt4 book ai didi

c - 程序终止而不打印

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:35 25 4
gpt4 key购买 nike

为什么我的 while 循环在终止前不打印我想要的打印语句?当我的程序退出时,我的打印语句都没有打印在终端中。我看不到循环可能退出的任何其他地方。

    while (1) {
int num_read;
// add the fd value into the fd_set value
FD_SET(sock_fd, &read_fds);
FD_SET(STDIN_FILENO, &read_fds);

// choose which fds to watch
select(sock_fd + 1, &read_fds, '\0', '\0', '\0');

if (FD_ISSET(STDIN_FILENO, &read_fds)) { //check whether the fd value is in the fd_set

num_read = read(STDIN_FILENO, buf, BUF_SIZE);
if (num_read == 0) {
printf("Print statement before terminating");
break;
}
buf[num_read] = '\0'; // Just because I'm paranoid

int num_written = write(sock_fd, buf, num_read);
if (num_written != num_read) {
perror("client: write");
printf("Print statement before terminating");
close(sock_fd);
printf("Print statement before terminating");
exit(1);
}
}

if (FD_ISSET(sock_fd, &read_fds)) { //the socket with the server
num_read = read(sock_fd, buf, BUF_SIZE);
buf[num_read] = '\0';
printf("%s", buf);
}
}
printf("Print statement before terminating");
close(sock_fd);
printf("Print statement before terminating");
return 0;
}

最佳答案

Printf() 是一个使用库缓冲区的库函数。默认情况下,库使用内衬缓冲区机制在终端上打印数据。要使 printf() 立即打印消息,请在传递给 printf() 的每个字符串中使用“\n”。当进程终止时,缓冲区被刷新,这就是您得到打印件的原因。

请阅读此内容。 https://stackoverflow.com/a/36573578/5694959

关于c - 程序终止而不打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49605057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com