Chinaunix
标题:
求教aix上面的一个pthread socket server是否有内存泄露
[打印本页]
作者:
sinosinux
时间:
2012-08-11 18:35
标题:
求教aix上面的一个pthread socket server是否有内存泄露
在aix上用pthread开发多线程socket服务器,实验程序如下,发现长时间运行,进程的内存占用量会缓慢上涨,求指教程序是否有内存泄露,谢谢!!
# include <iostream>
# include <string>
# include <sstream>
# include <list>
# include <map>
# include <vector>
# include <pthread.h>
# include <semaphore.h>
# include <errno.h>
# include <stdio.h>
# include <stdlib.h>
# include <signal.h>
# include <unistd.h>
# include <algorithm>
# include <netdb.h>
# include <netinet/in.h>
# include <sys/types.h>
# include <sys/socket.h>
# include <sys/socketvar.h>
# include <arpa/inet.h>
# include <sys/time.h>
# include <sys/limits.h>
# include <time.h>
using namespace std;
pthread_mutex_t pinmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_attr_t tattr;
class Pin
{
public:
Pin() {};
Pin (int id, string nm)
{
fd = id;
name = nm;
}
Pin(int id, char* nm)
{
fd = id;
name = nm;
}
int fd;
string name;
};
map<int, Pin> pins;
class PEMutex
{
private:
pthread_mutex_t& _mutex;
public:
PEMutex(pthread_mutex_t& mutex):_mutex(mutex)
{
pthread_mutex_lock(&mutex);
}
~PEMutex()
{
pthread_mutex_unlock(&_mutex);
}
};
void* threadfunc(void* apin)
{
pthread_detach(pthread_self());
Pin* pin = (Pin*)apin;
int fd = pin->fd;
char buf[] = "hello client";
send(fd, buf, strlen(buf), 0);
cout << buf << ":" << pthread_self() << endl;
close(fd);
{
PEMutex mutex(pinmutex);
pins.erase(fd);
}
pthread_exit(0);
return NULL;
}
int main(int argc, char** argv)
{
int clientsocket;
int serversocket;
int port = 14000;
socklen_t client_len;
struct sockaddr_in client, LSocket;
int ret;
pthread_attr_init (&tattr);
pthread_attr_setstacksize (&tattr, PTHREAD_STACK_MIN * 1024);
memset(&LSocket, 0, sizeof(LSocket));
LSocket.sin_family = AF_INET;
LSocket.sin_port = htons(port);
serversocket = socket (AF_INET, SOCK_STREAM, 0);
if (serversocket < 0)
{
cout << "socket failed:"<< errno << endl;
exit(1);
}
int option = 1;
if (setsockopt (serversocket, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option) ) < 0 )
{
cout << "setsockopt failed:"<< errno << endl;
exit(1);
}
ret = bind (serversocket, (struct sockaddr *)&LSocket, sizeof(struct sockaddr));
if (ret < 0) {
cout << "bind failed:"<< errno << endl;
exit(1);
}
listen(serversocket, 5);
client_len = sizeof(struct sockaddr_in);
cout << "start listen at:" << port << endl;
while(1) {
clientsocket = accept(serversocket, (struct sockaddr *)&client, &client_len);
if (clientsocket > 0)
{
stringstream portSS;
portSS << ntohs (client.sin_port);
string cliName = string(inet_ntoa (client.sin_addr)) + ":" + portSS.str();
cout << cliName << endl;
{
PEMutex mutex(pinmutex);
Pin pin(clientsocket, cliName.c_str());
pins[clientsocket] = pin;
pthread_t hdl;
int ret = pthread_create(&hdl, &tattr, threadfunc, &pins[clientsocket]);
}
}
else
{
cout << "accept failed:" << errno << endl;
sleep (1);
}
}
return 0;
}
复制代码
欢迎光临 Chinaunix (http://bbs.chinaunix.net/)
Powered by Discuz! X3.2