[英]Socket programming: combine data from fork()-ed processes
我是一名学生,从事C / C ++的Unix套接字/网络编程项目。 我正在编写一个可以从多个客户端接收TCP消息的简单服务器。 遵循本指南,我已编写了服务器以accept()
传入的客户端连接,然后使用fork()
来处理向每个客户端回送消息的情况。 到目前为止,一切都很容易。
现在,我需要获取在每个fork()
ed子进程中收集的数据,将其传递回执行accept()
ing的父进程,并允许父级继续使用收集的数据运行,并让每个子进程运行return 0;
。 (1个进程->许多进程收集数据-> 1个进程包含所有数据)
我不知道这样做的最好方法。 我的课程讲授网络,而不是Unix中的进程管理。 子进程如何将数据发送回父级? 还是他们可以以某种方式在彼此之间共享数据? 还是我完全以错误的方式来对待这个问题?
在分支的子服务器与其父服务器之间进行通信的常用方法是管道。 这是一个例子:
#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;
}
您还可以在本地主机上使用共享内存或套接字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.