それがどのように機能するかについては、実際には非常にプラットフォーム固有です。
Linuxシステムで実行している場合は、それほど難しくはありませんが、「フォーク」を使用してプロセスのコピーを生成するだけで、次のようなトリックが実行されます。
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet.h>
#include <signal.h>
#include <unistd.h>
int main()
{
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_Address.sin_port = htons(1234);
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
listen(server_sockfd, 5);
signal(SIGCHLD, SIG_IGN);
while(1)
{
char ch;
printf("Server Waiting\n");
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len)
// Here's where we do the forking, if you've forked already then this will be the child running, if not then your still the parent task.
if(fork() == 0)
{
// Do what ever the child needs to do with the connected client
read(client_sockfd, &ch, 1);
sleep(5); // just for show :-)
ch++;
write(client_sockfd, &ch, 1);
close(client_sockfd);
exit(0);
}
else
{
// Parent code here, close and loop for next connection
close(client_sockfd);
}
}
}
テストコンパイルを行うには、現時点ではLinuxボックスの近くにいないので、そのコードを少しいじる必要があるかもしれません。ほとんどメモリから入力しました。
ただし、Linux / UnixベースのシステムのCでこれを行うには、フォークを使用するのが標準的な方法です。
Windowsの下では、これは非常に異なる話であり、必要なすべてのコードを完全に思い出せないものです(最近、C#でのコーディングに慣れています)が、ソケットの設定は、使用する必要があることを除いてほとんど同じです。互換性を高めるための「Winsock」API。
(とにかく)標準のバークレーソケットを窓の下で使用することはできますが、落とし穴や穴がたくさんあります。窓のウィンソックの場合、これは開始するのに適した場所です。
http://tangentsoft.net/wskfaq/
私の知る限り、Winsockを使用している場合は、スポーンとマルチクライアントに役立つものがありますが、私自身は通常、別のスレッドをスピンオフしてソケット接続をコピーしてから、に戻ります。サーバーをリッスンしているループ。