c++ - C++ 在 ubuntu 上的意外行为

标签 c++ sockets ubuntu

我正在 Ubuntu 上编写一个简单的 C++ 应用程序。

int main()
{
    printf("Just a test line"); 
    Server();
    cout << "2"; 
return 1;
}

尽管服务器功能是什么,应用程序在控制台上写入任何内容之前就开始执行它(即只是一条测试线)


我的详细问题:


请查看随附的整个应用程序,其中 server() 负责监听端口 4444 上的连接。

#include <stdio.h>
#include <sys/types.h>
#include <cstdlib>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <strings.h>
#include <cstring>
#include <pthread.h>
#include <algorithm>
#include <iostream>
#include "message.h"
using namespace std;

#define iPort 4444

void Server(){
    cout << "3"; 
    int sockfd, newsockfd, n;
    socklen_t clilen;
    message m; // predefined class
    char *buffer = (char *) malloc (sizeof (m));
    struct sockaddr_in serv_addr, cli_addr;
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
        cerr << "ERROR opening socket";
    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(iPort);
    serv_addr.sin_addr.s_addr = INADDR_ANY;
    if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
        cerr << "ERROR on binding"<< endl;
    listen(sockfd,5);
    clilen = sizeof(cli_addr);
    int pid =0;
    while (1)
    {
        newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
        if (newsockfd < 0)
            cerr << "ERROR on accept" << endl;
        pid = fork();
        if (pid < 0)
            cerr << "ERROR on fork"<< endl;
        if (pid == 0)
        {
            close(sockfd);
            bzero(buffer,sizeof(m));
            buffer= (char*)&m;
            n = read(newsockfd,buffer,sizeof(m));
            if (n < 0) cerr << "ERROR reading from socket"<< endl;
            exit(0);
        }
        else close(newsockfd);
    }
}

int main()
{
    printf("Just a test line"); 
    Server();
    cout << "2"; 
return 1;
}

我通过终端执行命令如下:

pc@pc-SM40P:~/Desktop/LCR$ g++ -Wall -W -Werror main.cpp -o prog
pc@pc-SM40P:~/Desktop/LCR$ sudo ./prog

我原本希望在屏幕上看到 Just a test line,但什么也没有出现。 在此先感谢您的帮助, 问候

最佳答案

默认情况下,输出到终端的标准输出是行缓冲的,因此直到换行符才会打印输出。更改为:

printf("Just a test line\n"); 

或在 printf() 行之后调用 fflush(stdout)

关于c++ - C++ 在 ubuntu 上的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26822315/

相关文章:

c++ - POCO C++ 库文档有错误吗?

c++ - 取消引用 end() 是否安全?

perl 套接字 : increment port if in use

Linux:在进程 ID 完成或被杀死后发送邮件

ubuntu - ldconfig 无法识别目录中的新库

c++ - 在 Eclipse CDT 中指定外部 Makefile 选项

c++ - 为什么此 C++ 代码不起作用 - 尝试删除集合中的元素时常量引用错误

java - "Pinging"Java 中的服务器

c - 无效的读写valgrind

ubuntu - 无法声明 USB 接口(interface)(设备或资源繁忙)