gpt4 book ai didi

c++ - 为什么 accept() (用于套接字连接)导致我的代码阻塞?

转载 作者:行者123 更新时间:2023-11-28 07:02:51 25 4
gpt4 key购买 nike

当我运行代码时,当这一行时它似乎没有运行整个主函数

connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len); 

在里面。它甚至不会在开始时打印第一个 cout,但是当我将其注释掉时它工作正常,有人可以告诉我这是什么原因吗?

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <netinet/in.h>
#include <iostream>

#define PORT 1227
#define SIM_LENGTH 10;
using namespace std;
void clean_up(int cond, int *sock){
cout<<"exiting";
close(*sock);
exit(cond);
}

int main(void){
cout<<"working;
int sock;
int connect_sock;
struct sockaddr_in serv_name;
size_t len;
int count;

sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock<0){
cout<<"Error connecting to socket";
clean_up(1, &sock);
}
bzero(&serv_name, sizeof(serv_name)); // set name as physical address
serv_name.sin_family = AF_INET;
serv_name.sin_port = htons(PORT);
if(bind(sock,(struct sockaddr *)&serv_name, sizeof(serv_name))<0){
cout<<"error naming channel";
clean_up(1, &sock);
}
cout<<"waiting for connection from client";
listen(sock, 1);
len = sizeof(serv_name);
connect_sock = accept(sock, (struct sockaddr *)&serv_name, &len);
cout<<connect_sock;
cout<<"server wrote";
close(connect_sock);
cout<<"connect?";
}

最佳答案

它正在等待连接。它不会打印第一个 cout,因为您没有要求它打印。尝试:

cout<<"waiting for connection from client"<<endl;

关于c++ - 为什么 accept() (用于套接字连接)导致我的代码阻塞?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183227/

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