1.多进程:
启动多个进程,每个进程执行和一个客户端交互的程序
- accept()创建子进程,由子进程和客户端通讯,父进程继续接受客户端连接
- 启动多个进程,每个进程执行和一个客户端交互的程序
- 父进程完成与客户端的连接工作,完成后,创建子进程,子进程与客户端具体交互
- 子进程继承父进程打开的文件描述符(accept返回的文件描述符)
- 父进程必须关闭文件描述符
代码实现:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <assert.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
void CommClient(int c)
{
while(1)
{
char buff[128] = {0};
int n =recv(c,buff,127,0);
if(n<=0)
{
close(c);
printf("%d over\n",c);
break;
}
printf("%d:%s\n",c,buff);
}
}
int main()
{
int sockfd = socket(AF_INET,SOCK_STREAM,0);
assert(sockfd != -1);
struct sockaddr_in ser,cli;
memset(&ser,0,sizeof(ser));
ser.sin_family = AF_INET;
ser.sin_port = htons(6000);
ser.sin_addr.s_addr = inet_addr("127.0.0.1");
int res = bind(sockfd,(struct sockaddr*)&ser,sizeof(ser));
assert(res != -1);
listen(sockfd,5);
while(1)
{
int len = sizeof(cli);
int c = accept(sockfd,(struct sockaddr *)&cli,&len);
if(c<0)
{
printf("link error\n");
continue;
}
pid_t n = fork();
assert(n != -1);
if(n == 0)
{
CommClient(c);
exit(0);
}
else
{
close(c);
}
}
close(sockfd);
}
我们可以看到,开启了两个客户端,与一个服务器进行连接,形成两个进程
2.多线程:
启动多个线程,每个线程执行和一个客户端交互的程序
- accept();创建函数线程,由函数线程和客户端通讯,主线程继续接受客户连接
- 启动多个线程,每个线程执行和一个客户端的交互程序
- 函数线程要拿到与客户连接的文件描述符需要在创建线程时,以值传递的方式传递给函数线程(不能使用地址传递)
- 主线程不需要关闭文件描述符,因为同一个进程中的所有线程共享进程资源,仅有独立的栈区
- 多线程中不需要处理僵死进程,因为它本身不会fork出子进程
代码实现:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<assert.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<signal.h>
#include<pthread.h>
void* commCli(void* data)//与客户端交互
{
int c=(int)data;
while(1)
{
char buff[128]={0};
int n=recv(c,buff,127,0);
if(n<=0)
{
close(c);
printf("%d over\n",c);
break;
}
printf("%d: %s\n",c,buff);
send(c,"ok",2,0);
}
}
int main()
{
int sockfd=socket(AF_INET,SOCK_STREAM,0);
assert(sockfd!=-1);
struct sockaddr_in ser,cli;
memset(&ser,0,sizeof(ser));
ser.sin_family=AF_INET;
ser.sin_port=htons(6000);
ser.sin_addr.s_addr=inet_addr("127.0.0.1");
int res=bind(sockfd,(struct sockaddr*)&ser,sizeof(ser));
assert(res!=-1);
listen(sockfd,5);
while(1)
{
int len=sizeof(cli);
int c=accept(sockfd,(struct sockaddr*)&cli,&len);
if(c<0)
{
printf("link error\n");
continue;
}
pthread_t id;
int res=pthread_create(&id,NULL,commCli,(void *)c);
assert(res==0);
}
close(sockfd);
}
3.多进程与多线程的区别:
- 进程是资源分配的最小单位,同一进程中的线程共享进程的部分资源,如全局变量
- 线程是调度的基本单位
- 一个进程至少有一个线程,可以有多个线程
- 进程之间是相互独立的,相互之间没有影响。但是一个线程可以创建和撤销另一个线程
- 进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程之间没有单独的地址空间,一个线程死掉就等于整个进程死掉