C的printf和fprintf(标准输出)不打印 [英] C's printf and fprintf(stdout,) are not printing
问题描述
这是一个有点古怪的一种。我的code的不输出什么,我想它应该。我说在不同阶段的一些打印语句,看是去哪儿错了。依然没有。
所以,我在主开始增加了一个printf语句。这就是我真是糊涂了。
This is a bit of an odd one. My code wasn't outputting what I thought it should. I added some print statements at various stages to see where it was going wrong. Still nothing. So I added a printf statement at the start of main. That's where I got really confused.
所以我presumed一些有趣的事情是与文件描述符发生。我改变了的printf
到 fprintf中
。依然没有。印刷与标准错误fprintf中
确实工作!为什么会出现这种情况?
So I presumed something funny was happening with the file descriptors. I changed the printf
to a fprintf
. Still nothing. Printing to stderr with fprintf
does work! Why is this happening?
删除所有身体的主营除了最初的打印语句和返回可以打印。
Removing all of the body from main except the initial print statement and the return does print.
int main(void) {
fprintf(stdout, "STARTED!");
//Create an Internet domain socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
//If this fails exit and print the error
if (sockfd == -1) {
printf("Error %d, cannot create socket", errno);
return 1;
}
printf("SOCKET CREATED!");
//Creates a socket address
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8080);
addr.sin_addr.s_addr = INADDR_ANY;
//Attempts to bind to the socket address, again prints to error if this fails.
if (bind(sockfd, (struct sockaddr *) &addr, sizeof(addr)) == -1)
{
printf("Error %d, cannot bind", errno);
return 1;
}
//Starts Listening for a client
if (listen(sockfd, 1) == -1)
{
printf("Error %d, cannot listen", errno);
return 1;
}
//If all is successful, server is operational
while(1)
{
//Creates a file descripter for the connection
int connfd;
//And a socket address for the client
struct sockaddr_in cliaddr;
socklen_t cliaddrlen = sizeof(cliaddr);
//If a connection attempt is made accepts it.
connfd = accept(sockfd, (struct sockaddr *) &cliaddr, &cliaddrlen);
if (connfd == -1) {
//If the connection fails print an error
printf("Error %d, cannot accept connection", errno);
continue;
}
//Otherwise process the request
else {
printf("CONNECTED!");
char end;
end = 1;
while (end)
{
process_request(connfd);
end = 0;
}
}
close(connfd);
}
close(sockfd);
return 0;
}
推荐答案
输出通常是由系统缓冲。您可以拨打fflush,但有时,这取决于缓存是如何工作的,简单地结束与一个新行输出就足够了。因此,尝试改变
Output is often buffered by the system. You can call fflush, but sometimes, depending on how the caching works, simply ending the output with a newline is sufficient. So try changing
fprintf(stdout, "STARTED!");
到
fprintf(stdout, "STARTED!\n");
和,如果不帮忙,
fprintf(stdout, "STARTED!\n");
fflush(stdout)
(和标准错误往往没有被缓存,只要你想立即看到错误。)
(And stderr often isn't cached, as you want to see errors immediately.)
最后,你会看到输出的程序完成时(如东西被刷新的话),这可能说明了其行为的其余部分。
Finally, you will see output when the program finishes (as things are flushed then), which probably explains the rest of the behaviour.
这篇关于C的printf和fprintf(标准输出)不打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!