我的终端不断创建和分叉。我认为我的代码做错了,我实际上想要在客户端连接时分叉,但是当我启动服务器时,当我使用 linux 命令“ps”检查时,它会一直分叉,我如何更改我的代码以使其工作适当地。
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/un.h>
#include <sys/types.h>
#include <sys/socket.h>
using namespace std;
int main()
{
int serverFd;
int clientFd;
int serverLen;
int clientLen;
string message;
string serverSockAddrPtr;
struct sockaddr* serverSockAddressPnt;
struct sockaddr* clientSockAddressPnt;
struct sockaddr_un serverAddress;
struct sockaddr_un clientAddress;
// SOCKET CREATION PART - SERVER
serverFd = socket (AF_LOCAL, SOCK_STREAM, 0);
/* Set domain type */
serverAddress.sun_family = AF_LOCAL;
/* Set name */
strcpy (serverAddress.sun_path, "CountryServer");
/* GET SIZE OF Server Addres */
serverLen = sizeof serverAddress;
/* GET SIZE OF Client Addres */
clientLen = sizeof clientAddress;
/* Get Server Sock Address Pointer*/
serverSockAddressPnt = (struct sockaddr *) &serverAddress;
/* Get Client Sock Address Pointer*/
clientSockAddressPnt = (struct sockaddr *) &clientAddress;
/* Create file */
bind (serverFd, serverSockAddressPnt , serverLen);
/* listen for connection */
listen (serverFd,5);
// SOCKET CREATION END - SERVER
while(1)
{
//accept client connection
clientFd = accept(serverFd, clientSockAddressPnt, (socklen_t*)&clientLen);
if(fork()==0)
{
message="Successfully connected to the server";
write(clientFd,message.c_str(),strlen(message.c_str())+1);
close(clientFd);
exit(0);
}
else
close(clientFd);
}
return 0;
}
我的问题是:我如何让服务器在连接时分叉一个进程来处理客户端查询。
我不希望它无缘无故地分叉。感谢大家的帮助,这是我第一次使用 C 编码来学习更多关于编程的知识。
我的客户端和服务器通过 localhost、sockaddr_un 而不是互联网进行通信。