【问题标题】:Socket programming: combine data from fork()-ed processes套接字编程:组合来自 fork()-ed 进程的数据
【发布时间】:2014-04-15 09:36:13
【问题描述】:

我是一名学生,从事 C/C++ 中的 Unix 套接字/网络编程项目。我正在编写一个可以从多个客户端接收 TCP 消息的简单服务器。在this guide 之后,我将服务器写入accept() 传入客户端连接,然后fork() 处理向每个客户端来回发送一些消息。到目前为止,一切都很容易。

现在,我需要获取在每个fork()-ed 子进程中收集的数据,将其传递回执行accept()-ing 的父进程,并允许父进程继续使用收集的数据运行,然后让每个孩子return 0;。 (1 个进程 -> 多个进程收集数据 -> 1 个进程包含所有数据)

我不知道最好的方法。我的课程教授网络,而不是在 Unix 中管理进程。子进程如何将数据发送回父进程?或者,他们能否以某种方式在彼此之间共享数据?或者,我是否完全以错误的方式接近这个?

【问题讨论】:

  • 最简单的事情可能是使用pthread_create 启动一个函数来处理每个接受的客户端连接,然后您可以轻松地让线程生成它们的数据并告诉主接受线程它(该线程可以将void*s 收集到数据中,因为这是退出线程作为其控制线程pthread_joins 返回的“结果”类型。)。

标签: c++ sockets unix networking fork


【解决方案1】:

在分叉的子服务器与其父服务器之间进行通信的常用方法是管道。这是一个例子:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int
main(int argc, char * argv[])
{
   int pipefd[ 2];
   pid_t cpid;
   char buf;

   pipe( pipefd); // create the pipe
   cpid = fork(); // duplicate the current process
   if (cpid == 0) // if I am the child then
   {
       close( pipefd[ 0]); // close the read-end of the pipe
       write( pipefd[ 1], argv[0], strlen(argv[0])); // send name to the server
       close( pipefd[ 1]); //close the write-end of the pipe,
                           //send EOF to the server
       exit( EXIT_SUCCESS);
   }
   else // if I am the parent then
   {
       close( pipefd[ 1]); // close the write-end of the pipe
       while ( read( pipefd[ 0], &buf, 1) > 0) // read while EOF
           write( 1, &buf, 1);
       write( 1, "\n", 1);
       close( pipefd[0]); // close the read-end of the pipe
       wait( NULL); // wait for the child process to exit before I do the same
       exit( EXIT_SUCCESS);
   }
   return 0;
}

您还可以在本地主机上使用共享内存或套接字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 2021-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多