从其他流程服务器写入客户端

时间:2020-03-31 18:46:19

标签: c sockets server pipe

我有一个由主服务器和一些从服务器组成的服务器(例如一个)

我希望主服务器在连接时分发客户端。

//Initialisation
struct sockaddr_in clientaddr;
socklen_t clientlen;
clientlen = (socklen_t)sizeof(clientaddr);
int listenfd = Open_listenfd(PORT);

//Children instanciation here
int pipe_in = 0;
for (int i = 0; i < NPROC; i++)
{
    int p[2];
    pipe(p);
    children[i].id=Fork();
    if(children[i].id == 0){
        close (p[1]);
        pipe_in=p[0];
        goto CHILDREN;
    }
    else{
        close (p[0]);
        children[i].pipe_to = p[1];
    }
}


//Master Loop
int curchild = 0;
while (1) {
    int connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
    write(children[curchild].pipe_to, &connfd, sizeof(connfd));
    printf("Sent to slave %d\n",connfd);
    curchild = Next(curchild);
}

return 0;


//Slave Process
CHILDREN :
while (1) {
    int connfd;
    read(pipe_in, &connfd, sizeof(connfd));
    printf("Receveid from master %d\n",connfd);
    Rio_writen(connfd, "Test\n", 5);
    Close(connfd);
}

这里发送的描述符和接收的id相似,但是Rio_writen返回错误:错误的文件描述符

1 个答案:

答案 0 :(得分:1)

文件和套接字描述符只有在创建子进程之前打开时才传递给子进程。

例如:

  • 父级:接受新的TCP请求(从而收到新的GET karl/_search { "query": { "bool": { "must": [ { "match": { "tags": "programmer" } }, { "match": { "tags": "awesome" } } ] } } }
  • 父母:叉子,创造了一个新孩子
  • 父母:将connfd传递给新孩子
  • Child:处理套接字连接

更多信息:How can I pass a socket from parent to child processes - StackOverflow