作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
这是我从 microsoft 中获取的服务器代码.下面是我的 main,它需要运行 void important_code(bool);
。在 linux 和 windows 上使用管道和套接字时,我总是遇到这个问题。
我如何退出 select()
我什么时候想退出我的应用程序?假设 important_code 总是在套接字代码之后的同一个线程上执行。我该怎么做?
我知道这是 windows 代码,但我在 linux 下也遇到了这个问题
额外的测试代码:如果您在我的主函数中注释掉 main2() 并取消注释循环,您可以使用 ctrl+c 干净地退出。使用套接字代码,阻塞 select
阻止我这样做。我该如何解决这个问题?
#pragma comment(lib, "Ws2_32.lib")
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <tchar.h>
#include <strsafe.h>
#define DEFAULT_FAMILY AF_UNSPEC
#define DEFAULT_SOCKTYPE SOCK_STREAM
#define DEFAULT_PORT "1234"
#define BUFFER_SIZE 23 // length of "WinCE Echo Test Packet"
void Print(TCHAR *pFormat, ...)
{
va_list ArgList;
TCHAR Buffer[256];
va_start (ArgList, pFormat);
(void)StringCchPrintf(Buffer, 256, pFormat, ArgList);
#ifndef UNDER_CE
_putts(Buffer);
#else
printf("%s",Buffer);
#endif
va_end(ArgList);
}
int main2 ()
{
SOCKET sock, SockServ[FD_SETSIZE];
int nFamily = DEFAULT_FAMILY;
int nSockType = DEFAULT_SOCKTYPE;
char *szPort = DEFAULT_PORT;
SOCKADDR_STORAGE ssRemoteAddr;
int i, nNumSocks, cbRemoteAddrSize, cbXfer, cbTotalRecvd;
WSADATA wsaData;
ADDRINFO Hints, *AddrInfo = NULL, *AI;
fd_set fdSockSet;
char pBuf[BUFFER_SIZE];
char szRemoteAddrString[128];
if(WSAStartup(MAKEWORD(2,2), &wsaData))
{
// WSAStartup failed
return 1;
}
sock = INVALID_SOCKET;
for(i = 0; i < FD_SETSIZE; i++)
SockServ[i] = INVALID_SOCKET;
//
// Get a list of available addresses to serve on
//
memset(&Hints, 0, sizeof(Hints));
Hints.ai_family = nFamily;
Hints.ai_socktype = nSockType;
Hints.ai_flags = AI_NUMERICHOST | AI_PASSIVE;
if(getaddrinfo(NULL, szPort, &Hints, &AddrInfo))
{
Print(TEXT("ERROR: getaddrinfo failed with error %d\r\n"), WSAGetLastError());
goto Cleanup;
}
//
// Create a list of serving sockets, one for each address
//
i = 0;
for(AI = AddrInfo; AI != NULL; AI = AI->ai_next)
{
if (i == FD_SETSIZE)
{
// getaddrinfo returned more addresses than we could use
break;
}
if((AI->ai_family == PF_INET) || (AI->ai_family == PF_INET6)) // only want PF_INET or PF_INET6
{
SockServ[i] = socket(AI->ai_family, AI->ai_socktype, AI->ai_protocol);
if (SockServ[i] != INVALID_SOCKET)
{
if (bind(SockServ[i], AI->ai_addr, AI->ai_addrlen) == SOCKET_ERROR)
closesocket(SockServ[i]);
else
{
if(nSockType == SOCK_STREAM)
{
if (listen(SockServ[i], 5) == SOCKET_ERROR)
{
closesocket(SockServ[i]);
continue;
}
}
Print(
TEXT("Socket 0x%08x ready for connection with %hs family, %hs type, on port %hs\r\n"),
SockServ[i],
(AI->ai_family == AF_INET) ? "AF_INET" : ((AI->ai_family == AF_INET6) ? "AF_INET6" : "UNKNOWN"),
(AI->ai_socktype == SOCK_STREAM) ? "TCP" : ((AI->ai_socktype == SOCK_DGRAM) ? "UDP" : "UNKNOWN"),
szPort);
i++;
}
}
}
}
freeaddrinfo(AddrInfo);
if (i == 0)
{
Print(TEXT("ERROR: Unable to serve on any address. Error = %d\r\n"), WSAGetLastError());
goto Cleanup;
}
//
// Wait for incomming data/connections
//
nNumSocks = i;
FD_ZERO(&fdSockSet);
for (i = 0; i < nNumSocks; i++) // want to check all available sockets
FD_SET(SockServ[i], &fdSockSet);
if (select(nNumSocks, &fdSockSet, 0, 0, NULL) == SOCKET_ERROR)
{
Print(TEXT("ERROR: select() failed with error = %d\r\n"), WSAGetLastError());
goto Cleanup;
}
for (i = 0; i < nNumSocks; i++) // check which socket is ready to process
{
if (FD_ISSET(SockServ[i], &fdSockSet)) // proceed for connected socket
{
FD_CLR(SockServ[i], &fdSockSet);
if(nSockType == SOCK_STREAM)
{
cbRemoteAddrSize = sizeof(ssRemoteAddr);
sock = accept(SockServ[i], (SOCKADDR*)&ssRemoteAddr, &cbRemoteAddrSize);
if(sock == INVALID_SOCKET)
{
Print(TEXT("ERROR: accept() failed with error = %d\r\n"), WSAGetLastError());
goto Cleanup;
}
Print(TEXT("Accepted TCP connection from socket 0x%08x\r\n"), sock);
}
else
{
sock = SockServ[i];
Print(TEXT("UDP data available on socket 0x%08x\r\n"), sock);
}
break; // Only need one socket
}
}
//
// Receive data from a client
//
cbTotalRecvd = 0;
do
{
cbRemoteAddrSize = sizeof(ssRemoteAddr);
cbXfer = recvfrom(sock, pBuf + cbTotalRecvd, sizeof(pBuf) - cbTotalRecvd, 0,
(SOCKADDR *)&ssRemoteAddr, &cbRemoteAddrSize);
cbTotalRecvd += cbXfer;
} while(cbXfer > 0 && cbTotalRecvd < sizeof(pBuf));
if(cbXfer == SOCKET_ERROR)
{
Print(TEXT("ERROR: Couldn't receive the data! Error = %d\r\n"), WSAGetLastError());
goto Cleanup;
}
else if(cbXfer == 0)
{
Print(TEXT("ERROR: Didn't get all the expected data from the client!\r\n"));
goto Cleanup;
}
if(nSockType == SOCK_STREAM)
{
cbRemoteAddrSize = sizeof(ssRemoteAddr);
getpeername(sock, (SOCKADDR *)&ssRemoteAddr, &cbRemoteAddrSize);
}
if (getnameinfo((SOCKADDR *)&ssRemoteAddr, cbRemoteAddrSize,
szRemoteAddrString, sizeof(szRemoteAddrString), NULL, 0, NI_NUMERICHOST) != 0)
strcpy(szRemoteAddrString, "");
Print(TEXT("SUCCESS - Received %d bytes from client %hs\r\n"), cbTotalRecvd, szRemoteAddrString);
//
// Echo the data back to the client
//
cbXfer = 0;
cbXfer = sendto(sock, pBuf, cbTotalRecvd, 0, (SOCKADDR *)&ssRemoteAddr, cbRemoteAddrSize);
if(cbXfer != cbTotalRecvd)
Print(TEXT("ERROR: Couldn't send the data! error = %d\r\n"), WSAGetLastError());
else
Print(TEXT("SUCCESS - Echo'd %d bytes back to the client\r\n"), cbXfer);
Cleanup:
for(i = 0; i < nNumSocks && SockServ[i] != INVALID_SOCKET; i++)
closesocket(SockServ[i]);
if(sock != INVALID_SOCKET)
{
shutdown(sock, SD_BOTH);
closesocket(sock);
}
WSACleanup();
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
volatile bool terminate_app=false;
void terminate (int param)
{
printf("Terminating program...\n");
terminate_app=true;
}
void important_code(bool v)
{
printf("Important code here %d\n", v);
}
int main ()
{
try{
void (*prev_fn)(int);
prev_fn = signal (SIGINT,terminate);
main2();
//while(terminate_app==false)
{
}
}
catch(...){
important_code(1);
}
important_code(0);
return 0;
}
最佳答案
在 POSIX 上 select()
将在超时时返回,或者当其中一个描述符准备就绪时返回,或者如果它被一个信号。
因此,您可以使用 EINTR
行为。只需使用 sigaction()
函数安装一个信号处理程序,而无需 SA_RESTART
(重新启动被信号中断的系统调用)标志。 (signal()
的行为因系统而异,在某些系统上,它可以通过 #defines
进行更改)。
或者,您可以使用自管道技巧:写入管道以发出您想要退出的信号。如果您的 select()
选择了该管道的读取描述符,它将返回。
关于c - 套接字阻塞 :( How do i get out?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9491633/
我是一名优秀的程序员,十分优秀!