代码:
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 6666 //1024~49151
#define IP "192.168.122.130" //ifconfig查看本机IP
#include <pthread.h>
//需要传入分之线程的数据类型
struct Climsg
{int newfd;struct sockaddr_in cin;
};
void *deal_cli_msg(void *arg);
int main(int argc, const char *argv[])
{//创建流式套接字int sfd = socket(AF_INET,SOCK_STREAM,0);if(sfd < 0){ERRO_MES("socket");return -1;}printf("sfd = %d\n",sfd);//绑定服务器的IP和端口--->必须绑定//填充地址信息结构体,真实的地址信息结构体根据地质族制定//AF_INET: man 7 ip;struct sockaddr_in sin;sin.sin_family = AF_INET;//必须填AF_INET;sin.sin_port = htons(PORT); //端口号:1024~49151;sin.sin_addr.s_addr = inet_addr(IP); //本机IP ifconfig查看;if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin)) < 0){ERRO_MES("bind");return -1;}printf("bind success\n");//将套接字设置为被动监听状态if(listen(sfd,10) < 0){ERRO_MES("listen");return -1;}printf("listen success\n");//设置允许端口号被快速复用int reuse = 1;if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0){ERRO_MES("setsockopt");return -1;}printf("允许端口快速重用成功\n");//从已完成链接的队列中获取一个客户端信息,生成一个新的文件//该文件描述符才是与客户端通信的文件描述符struct sockaddr_in cin;socklen_t addrlen = sizeof(cin);int newfd = -1;pthread_t tid;struct Climsg info;while(1){ //主线程只负责连接newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);if(newfd < 0){ERRO_MES("accept");return -1;}printf("[%s : %d] newfd = %d,客户端链接成功\n",\inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);info.newfd = newfd;info,cin =cin;if(pthread_create(&tid,NULL,deal_cli_msg,(void *)&info) != 0){fprintf(stderr,"pthread_create failed __%d__",__LINE__);return -1;}pthread_detach(tid); //分离线程}close(sfd);return 0;
}
void *deal_cli_msg(void *arg)
{int newfd = ((struct Climsg*)arg)->newfd;struct sockaddr_in cin = ((struct Climsg*)arg)->cin;//分之线程只负责交互//从指定的文件套接字char buf[128]="";ssize_t res = 0;while(1){bzero(buf,sizeof(buf));//接收数据res = recv(newfd,buf,sizeof(buf),0);if(res < 0){ERRO_MES("recv");break;}else if(0 == res){printf("[%s : %d] newfd = %d,客户下线\n",\inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);break;}printf("newfd :%d\t buf = %s\n",newfd,buf);//发送数据strcat(buf,"----");if(send(newfd,buf,sizeof(buf),0) < 0){ERRO_MES("send");break;}printf("send success\n");}close(newfd);pthread_exit(NULL);
}
一、多线程中的newfd,能否修改成全局,为什么?
答:不能修改成全局;
当使用全局变量时,线程中的newfd会发生覆盖;
二、多线程中分支线程的newfd能否不另存,直接用指针间接访问主线程中的newfd,为什么?
答:不能
现象表明,线程中的newfd会发生覆盖,只保留最后一次newfd的值