gpt4 book ai didi

C套接字recv()错误处理

转载 作者:行者123 更新时间:2023-11-30 15:49:53 24 4
gpt4 key购买 nike

我有一个关于套接字中的recv()函数的问题(在linux Raspberri Pi上)

为什么我的程序停止在:

if ((numbytes = recv(fd, odp, 100, 0)) == -1) {
printf("\n error while test recv 1");
perror("recv");
reconnect = 1;
}

是的,出现错误:“资源暂时不可用”

当我看到:printf("\n 测试接收 1 时出错");

我想处理稍后所做的重新连接。但我在终端窗口上看到我的程序停止在:

测试接收1时出错

我尝试过:

信号(SIGPIPE, SIG_IGN);

比:

信号(SIGPIPE, my_function);

但它停在任一处。

一些代码:

int main(int argc, char *argv[])
{

while(1) {

if(reconnect){
close(fd);
fd = createSocket(argv[1]);
reconnect=0;
}

reconnect = connectionTest(fd);

}


int connectionTest(int *fd) {

numbytes=send(fd, buf, 100,0);

if ((numbytes = recv(fd, reply, 100, 0)) == -1) {
/* HERE IT STOPS */
perror("recv");
printf("\n error while test recv 1");

reconnect = 1;

}

return reconnect;
}

int createSocket(char *server_addr){

int sockfd;
struct addrinfo hints, *servinfo, *p;
int rv;
char s[INET6_ADDRSTRLEN];
int set = 1;

signal(SIGPIPE, SIG_IGN);

printf("connect to: %s", server_addr);

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;

if ((rv = getaddrinfo(server_addr, PORT, &hints, &servinfo)) != 0) {
fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
return 1;
}

// loop through all the results and connect to the first we can
for(p = servinfo; p != NULL; p = p->ai_next) {
if ((sockfd = socket(p->ai_family, p->ai_socktype,
p->ai_protocol)) == -1) {
perror("client: socket");
continue;
}
else printf("socketd created! \n");

int set = 1;
setsockopt(sockfd, SOL_SOCKET, MSG_NOSIGNAL, (void *)&set, sizeof(int));

if (setsockopt( sockfd, SOL_SOCKET, SO_KEEPALIVE, (void *)&set, sizeof(int)) < 0 )
perror("setsockopt failed \n");

struct timeval timeout;
timeout.tv_sec = 4;
timeout.tv_usec = 0;


if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0 )
perror("setsockopt failed \n");

if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0 )
perror("setsockopt failed \n");

printf("Try to connect \n");
if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
close(sockfd);
perror("client: connect");
}
else {
printf("i have connection");
break;
}
}

printf("next1");

if (p == NULL) {
fprintf(stderr, "client: failed to connect\n");
return 2;
}

inet_ntop(p->ai_family, get_in_addr((struct sockaddr *)p->ai_addr),
s, sizeof s);
printf("client: connecting to %s\n", s);
freeaddrinfo(servinfo); // all done with this structure

return sockfd;
}

最佳答案

read()返回 EPIPE。

如果针对已被另一方 shutdown() 甚至 close()d 的连接发出 write()无论如何,发布过程都会出错。

发出SIGPIPE,如果没有处理也没有被阻止,进程将终止。如果 SIGPIPE 被处理或阻止,write() 应返回 -1 并将 errno 设置为 EPIPE.

关于C套接字recv()错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16039275/

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