简体   繁体   English

带套接字的许多消息队列

[英]Many Message Queues with socket

I've a program. 我有一个程序。 it creates a client socket(non-block), and also it will fork many child processes. 它创建一个客户端套接字(非阻塞),并且还将派生许多子进程。 The child processes just receiving messages from message queue and write it to the socket. 子进程仅从消息队列接收消息,然后将其写入套接字。 What happens if at the same time many child processes received message from their message queue and write it to the socket? 如果同时有许多子进程从其消息队列接收消息并将其写入套接字,会发生什么情况?

Below is the code: 下面是代码:

//create socket
sockfd = socket(AF_INET, SOCK_STREAM, 0);
connect(sockfd, (struct sockaddr *)&sin, sizeof(sin));

//set the socket to be non-block.
int fs = fcntl(sockfd, F_GETFL, 0);
fcntl(sockfd, F_SETFL, fs | O_NONBLOCK);

//fork many child processes for receiving message from message queue
for (i = 0, lp = listhead; lp != NULL; lp = lp->next) {
    switch (fork()) {
    case -1:
        slogsyscall("fork", errno);
        killpg(0, SIGTERM);
        _exit(EXIT_SYSCALL);
    case 0: /* child process */
        for(;;) {
            //receive message from message queue
            int rcvlen = msgrcv(lp->msqid, &pmsg.mtype, MAX_MTEXT, 0, 0);

            //write the received message to the non-block socket 'sockfd'
            write(sockfd, pmsg.msg, rcvlen);
        }
    default:
        break;
    }
}

I expect all the messages which sent to the non-block socket 'sockfd' will correctly sent and will not interfere with each other. 我希望所有发送到非阻塞套接字“ sockfd”的消息都将正确发送,并且不会互相干扰。

for example: 例如:

child process 1:   got message 'cat' from queue, and send it to sockfd
child process 2:   got message 'dog' from queue, and send it to sockfd
child process 3:   got message 'chicken' from queue, and send it to sockfd
child process 4:   got message 'monkey' from queue, and send it to sockfd

Does the socket will put the message in the socket buffer like this: catdogchickenmonkey with no particular order. 套接字是否会像下面这样将消息放入套接字缓冲区: catdogchickenmonkey ,没有特定的顺序。 or they will interfere with each other like cogdatchikmonkeyen ? 否则它们会像cogdatchikmonkeyen那样cogdatchikmonkeyen干扰?

If they interfere with each other, then how can i prevent this from happening? 如果它们相互干扰,那么我该如何防止这种情况发生?

If I change the socket to be blocking, then what happens? 如果我将套接字更改为阻塞状态,那会发生什么?

As discussed in the comments, you can use F_SETLK. 如注释中所述,您可以使用F_SETLK。 I am writing below code on the basis of manpage and have not compiled or tested. 我正在基于联机帮助页编写以下代码,但尚未编译或测试。

struct flock fl = {0};
int result;

/* Lock range for writing */
fl.l_type = FL_WRLCK;  /* Write lock */
/* from current to len bytes */
fl.l_whence = SEEK_CUR;
fl.l_start = 0;
fl.l_len = strlen(pmsg.msg); /* typecasting required */
fl.pid = mypid;

result = fcntl(sockfd, F_SETLK, &fl);
if (rc == -1) {
 perror("fcntl");
 /* Retry or something */
}

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

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