C的printf和fprintf(stdout,)没有打印

这有点奇怪.我的代码没有输出我认为应该的东西.我在各个阶段添加了一些打印语句,以查看它出错的地方.依然没有.
所以我在main的开头添加了一个printf语句.这就是我真的很困惑的地方.

所以我假设文件描述符发生了一些有趣的事情.我将printf更改为fprintf.依然没有.使用fprintf打印到stderr确实有效!为什么会这样?

除了初始打印语句之外,从main中删除所有主体并返回打印.

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,但有时,根据缓存的工作方式,只需使用换行符结束输出就足够了.所以尝试改变

fprintf(stdout, "STARTED!");

fprintf(stdout, "STARTED!\n");

并且,如果这没有帮助,那么

fprintf(stdout, "STARTED!\n");
fflush(stdout)

(并且stderr通常不会被缓存,因为您希望立即看到错误.)

最后,您将在程序完成时看到输出(然后刷新事物),这可能解释了其余的行为.

翻译自:https://stackoverflow.com/questions/14784367/cs-printf-and-fprintfstdout-are-not-printing

转载注明原文:C的printf和fprintf(stdout,)没有打印