簡體   English   中英

帶套接字的許多消息隊列

[英]Many Message Queues with socket

我有一個程序。 它創建一個客戶端套接字(非阻塞),並且還將派生許多子進程。 子進程僅從消息隊列接收消息,然后將其寫入套接字。 如果同時有許多子進程從其消息隊列接收消息並將其寫入套接字,會發生什么情況?

下面是代碼:

//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;
    }
}

我希望所有發送到非阻塞套接字“ sockfd”的消息都將正確發送,並且不會互相干擾。

例如:

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

套接字是否會像下面這樣將消息放入套接字緩沖區: catdogchickenmonkey ,沒有特定的順序。 否則它們會像cogdatchikmonkeyen那樣cogdatchikmonkeyen干擾?

如果它們相互干擾,那么我該如何防止這種情況發生?

如果我將套接字更改為阻塞狀態,那會發生什么?

如注釋中所述,您可以使用F_SETLK。 我正在基於聯機幫助頁編寫以下代碼,但尚未編譯或測試。

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