在我的应用程序中,我有一个使用以下代码接受新连接的守护进程。
int serverSocket = socket(AF_LOCAL, SOCK_STREAM, 0);
if (serverSocket < 0) {
fprintf(stderr, "Error (%d) while creating socket.",serverSocket);
return -1;
}
struct sockaddr_un server;
memset(&server, 0, sizeof server);
server.sun_family = AF_UNIX;
// the first byte of sun_path should be '\0' for abstract namespace
strcpy(server.sun_path + 1, sockname);
// note that sockaddr_len should be set to the exact size of the buffer that is used.
socklen_t sockaddr_len = sizeof(server.sun_family) + strlen(sockname) + 1;
if (bind(serverSocket, (struct sockaddr *) &server, sockaddr_len) < 0) {
close(serverSocket);
fprintf(stderr, "Failed to bind the server socket");
return -1;
}
if (listen(serverSocket, 1) < 0) {
close(serverSocket);
fprintf(stderr, "Failed to listen on server socket");
return -1;
}
int clientSocket = accept(serverSocket, (struct sockaddr *)&server, &sockaddr_len);
if (clientSocket < 0) {
close(serverSocket);
fprintf(stderr, "Failed to accept client connection");
return -1;
}
我的客户端连接成功,“接受”后我开始从 clientSocket 读取。当我从 clientSocket 读取时,我想阻止。相反,它看起来像读取是非阻塞的。服务器如何执行阻塞读取?
即使客户端没有发送数据,下面的“读取”也会立即返回而不会出错。
mSocket = clientSocket;
if (mSocket <= 0) {
return -1;
}
int n = read(mSocket, (uint8_t*)data, len);
if (n < 0) {
fprintf(stderr, "Error receiving data from stream: %d", errno);
return -1;
}
fprintf(stderr, "Reading %d bytes of %d data from stream\n", n, len);
我尝试使用 setSockOpt 命令在 clientSocket 上设置超时,但这不起作用。有任何想法吗?