概述
Linux C网络编程基础Socket只是作为入门示例,一个服务端同时只能连接一个客户端进行交互。若想实现连接多个客户端,则可考虑使用多进程编程。
原理
linux C提供了fork函数实现多进程程序,fork()函数返回进程ID(pid),可用于判断后续代码为子进程( pid==0 )还是父进程(pid>0)。
代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
printf( "%d: start program...\n", getpid() );
int pid = fork();
if( pid > 0 )
{
printf( "%d: this is father process...\n", getpid() );
}
else
{
printf( "%d: this is child process...\n", getpid() );
}
printf( "%d: end program...\n", getpid() );
}