简体   繁体   English

没有发送(或接收)队列的Unix套接字

[英]Unix Socket without sending (or receiving) queue

I have a sender/receiver pair of codes written in C and Python. 我有一对用C和Python编写的发送者/接收者代码对。 The client is producing data and send it over a unix socket to receiver. 客户端正在生成数据,并通过unix套接字将其发送到接收器。 Receiver is not always listening to the socket, because it should do something with received data. 接收器并不总是在监听套接字,因为它应该对接收到的数据执行某些操作。

In my current code all messages sent by sender are waiting in a queue to be received by receiver, but I don't want this behavior. 在我当前的代码中,发送方发送的所有消息都在队列中等待接收方接收,但是我不希望这种行为。 I want the sender know that the receiver is busy now (maybe even by raising an error). 我想让发送者知道接收者现在很忙(甚至可能引发错误)。 So how can I set the queue length of receiver to zero? 那么如何将接收者的队列长度设置为零?

Please consider that I don't want the send or receive procedure be blocking. 请考虑我不要阻止发送或接收过程。

My receiver and sender parts of codes are these: 我的接收方和发送方代码部分如下:

Receiver (in Python): 接收器(在Python中):

self.app_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
self.app_socket.settimeout(0.01)
self.app_socket.bind(APP_SOCKET)

def poll(self, *args):
    try:
        message = self.app_socket.recv(1024)
    except socket.timeout:
        return

Sender (in C): 发件人(以C表示):

int openSocket(char *path)
{
    int sock;
    struct sockaddr_un addr;
    int size;

    sock = socket(AF_UNIX, SOCK_DGRAM, 0);
    if (sock < 0)
        exit (EXIT_FAILURE);

    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, path);
    size = strlen(addr.sun_path) + sizeof(addr.sun_family);

    if (connect(sock, (struct sockaddr *) &addr, size) < 0)
        return -1;

    return sock;
}

int sendMessage(int sock, unsigned char *message, int length)
{
    int count;

    count = send(sock, message, length, 0);
    if (count < 0)
        return -1;

    return count;
}

You can't tell on sender side what is going on on the receiver. 您无法告诉发送方接收方发生了什么。 May be receiver process is not even scheduled now. 可能现在还没有安排接收器进程。 The only reasonable way is to answer from receiver back to sender, where you can wait some timeout for this answer and decide whether receiver busy or not. 唯一合理的方法是从接收方返回发送方,在那里您可以等待一些超时时间来确定答案,并确定接收方是否忙。

You need some way for the receiver to signal its state (read or not) to the sender. 您需要某种方式使接收方将其状态(已读或未读)发送给发送方。 There are several IPC primitives you might use for this purpose. 您可以为此使用多个IPC原语。

Or you could make up your own. 或者,您可以自己做。 For example the receiver could so something along these line: 例如,接收方可以按照以下方式进行操作:

    mkdir("/path/to/my/flag/dir", 0555);  /* ready */
    read();
    rmdir("/path/to/my/flag/dir");       /* busy */

and the sender could periodically check for existence of this with something along these lines: 发送者可以按照以下方式定期检查是否存在此问题:

    oktogo = (access("/path/to/my/flag/dir", F_OK) == 0);

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

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