标签:环境 pthread data get ack 实现 关闭 linux网络 turn
在我的里面已经介绍了linux以下c的进程、线程接口,这里就不做过多阐述了。
多进程
这里多进程採用传统的多进程模型。每当有client发来的连接时创建一个进程来处理连接,一个子进程相应一个连接。
有了上篇单一进程的基础,此处仅仅做简单的改动便能够实现。
while(1){
clientfd = Accept(servfd, (struct sockaddr*)&cliaddr, &clientlen);
host = Gethostbyaddr((const char*)&cliaddr.sin_addr.s_addr, sizeof(cliaddr.sin_addr.s_addr), AF_INET);
printf("server connect to host: %s %s\n",host->h_name, inet_ntoa(cliaddr.sin_addr));
if ((child_pid = Fork()) == 0){
Close(servfd);
echo(clientfd);
Close(clientfd);
}
Close(clientfd);
}仅仅须要在while里面加入进程的创建就可以,然后在子进程里先关闭父进程的监听套接字。
当然。不要忘了在上面加入Fork错误处理的包裹函数(在Fork一节中已讲到)。
void error_msg(char *msg){
perror(msg);
exit(0);
}
int Fork(){
pid_t pid;
if ( ( pid = fork() ) < 0 )
error_msg("fork failed");
return pid;
}client:
server:
多线程
线程和进程在非常多方面是相通的,仿照上面的多进程的传统模型。不难实现多线程的传统模型。
依旧是在while里面做简单的改动就可以。
clientfd = (int*)malloc(sizeof(int));
*clientfd = Accept(servfd, (struct sockaddr*)&cliaddr, &clientlen);
host = Gethostbyaddr((const char*)&cliaddr.sin_addr.s_addr, sizeof(cliaddr.sin_addr.s_addr), AF_INET);
printf("server connect to host: %s %s\n",host->h_name, inet_ntoa(cliaddr.sin_addr));
Pthread_create(&tid, NULL, &thread, clientfd);
Close(*clientfd);
线程函数为
void *thread(void* arg){
int clientfd = *((int*)arg);
free(arg);
Pthread_detach(pthread_self());
echo(clientfd);
close(clientfd);
return NULL;
}
执行结果:
这段代码有个问题,clientfd传入线程之后。arg指针没有接收到值,指在了一个无法訪问的地方(gdb显示值为0x00),百思不得其解。
(原理非常easy,遇到的问题先记录下,假设有人知道错在哪里希望能指正出来。。
。
环境 ubuntu 64位,编译器gcc)
标签:环境 pthread data get ack 实现 关闭 linux网络 turn
原文地址:http://www.cnblogs.com/brucemengbm/p/6920619.html