いくつかの不可解な理由により、このC++プログラムはソケットを受け入れると終了します。ソケットは受け入れられ、クライアント側に反映されますが、サーバーは自然に爆発します。
完全なコードは次のとおりです。
#include <sys/types.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <string.h>
#include <errno.h>
#define BUF_SIZE 500
#define BACKLOG 50
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Usage %s port\n", argv[0]);
exit(EXIT_FAILURE);
}
struct sockaddr_in addr;
struct sockaddr_storage theiraddr;
socklen_t addrlen;
char buf[BUF_SIZE];
addr.sin_family = AF_INET;
addr.sin_port = htons(atoi(argv[1]));
addr.sin_addr.s_addr = INADDR_ANY;
theiraddr.ss_family = AF_INET;
int sockfd = socket(AF_INET, SOCK_STREAM|SOCK_NONBLOCK, 0);
if (sockfd == -1)
{
printf("Sock Error!\n");
exit(EXIT_FAILURE);
}
if (bind(sockfd, (struct sockaddr*)&addr, sizeof(addr)) == -1)
{
printf("Bind Error!\n");
exit(EXIT_FAILURE);
}
if (listen(sockfd, BACKLOG) == -1)
{
printf("Listen Error!\n");
exit(EXIT_FAILURE);
}
addrlen = sizeof(theiraddr);
int accepted;
for ( int i = 0; ; i++ )
{
usleep(100000);
errno = 0;
printf("pre-accept\n");
accepted = accept(sockfd, (struct sockaddr *)&theiraddr, &addrlen);
printf("%i", accepted == -1); //this line does not get executed
if(errno == EWOULDBLOCK)
{
printf("WOULDBLOCK %i\n", i);
continue;
}
else if(accepted == -1)
{
printf("TERRIBLE TRAGEDY\n");
}
printf("Accepted.\n");
char msg[] = "You have connected.";
send(sockfd, msg, sizeof(msg), 0);
close(accepted);
}
close(sockfd);
}