简体   繁体   English

阻止套接字到非阻止套接字

[英]Blocking sockets to non-blocking sockets

Can anyone help me, how to change the below code to non-blocking 谁能帮我,如何将以下代码更改为非阻塞

struct sockaddr_un server_address;
int server_len, err;
int ret = 1;

int ipc_sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
if (ipc_sockfd < 0) {
    printf("%s\n","SHM_IPC: socket creation failed");
    return 0;
}
server_address.sun_family = AF_UNIX;
strcpy(server_address.sun_path, SHM_IPC_SOCKET_NAME);
server_len = sizeof(server_address);

err = connect(ipc_sockfd, (struct sockaddr*)&server_address,
              server_len);
if (err < 0) {
    printf("%s %d\n", "IPC socket server not ready for"
                            ". Try after few moments, Errno:", errno);
    close(ipc_sockfd);
    return 0;
}

err = write(ipc_sockfd, (void *)msg, sizeof(shm_ipc_msg));
if (err <=0) {
    printf("%s %d\n", "SHM_IPC: socket write failed:",errno);
    ret = 0;
}
close(ipc_sockfd);
return ret;

This is my client side socket, i need my client side write() and connect() to be non-blocking (I dont care about server side), do I need to change the server socket also to non-blocking to take effect? 这是我的客户端套接字,我需要我的客户端write()和connect()是非阻塞的(我不在乎服务器端),我是否需要将服务器套接字也更改为非阻塞才能生效?

Really appreciate your help! 非常感谢您的帮助!

This thread might help you: Does connect() block for TCP socket? 此线程可能会帮助您: TCP套接字的connect()是否阻塞?

You can make your connect non-blocking but for what reason? 您可以使连接成为非阻塞,但是出于什么原因呢? if the client is not connected to the server you cannot expect socket.write to work. 如果客户端未连接到服务器,则无法期望socket.write正常工作。 You need to wait until the connection it's done. 您需要等待直到连接完成。 The write operation though it is not a blocking operation. 写操作虽然不是阻塞操作。 If the connection is established the write function should return immediately after sending your data. 如果建立了连接,则写函数应在发送数据后立即返回。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM