新建一个线程跑服务端,并且设置stacksize的示例代码
#include <stdio.h>
#include <pthread.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <poll.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <sys/resource.h>
#include <string>
pthread_t new_tid;
#define MAXLINE 4096
const int EPOLL_MAX_FDSIZE = 0x4000;
void printThread(const char* s)
{
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("%s, pid is %lu, tid is %x
", s, (unsigned long)pid, (unsigned long)tid);
int i, maxi, listenfd, connfd, sockfd, epfd, nfds;
int n;
char buf[MAXLINE];
struct epoll_event ev, events[EPOLL_MAX_FDSIZE];
socklen_t clilen;
//struct pollfd client[OPEN_MAX];
std::string content = "RTSP/1.0 200 OK
CSeq: 2502
";
struct sockaddr_in cliaddr , servaddr;
listenfd = socket(AF_INET , SOCK_STREAM , 0);
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(1655);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(listenfd , (struct sockaddr *) & servaddr, sizeof(servaddr));
listen(listenfd,10);
epfd = epoll_create(EPOLL_MAX_FDSIZE);
ev.data.fd=listenfd;
ev.events=EPOLLIN|EPOLLET;
epoll_ctl(epfd,EPOLL_CTL_ADD,listenfd,&ev);
for(;;)
{
nfds=epoll_wait(epfd,events,EPOLL_MAX_FDSIZE,50);
for(i=0; i<nfds; i++)
{
if (listenfd == events[i].data.fd)
{
clilen = sizeof(cliaddr);
connfd = accept(listenfd , (struct sockaddr *)&cliaddr, &clilen);
if(connfd < 0)
{
perror("connfd < 0");
}
ev.data.fd=connfd;
ev.events=EPOLLIN|EPOLLET;
epoll_ctl(epfd,EPOLL_CTL_ADD,connfd,&ev);
}
else if (events[i].events & EPOLLIN)
{
if ( (sockfd = events[i].data.fd) < 0)
continue;
n = recv(sockfd,buf,MAXLINE,0);
if (n <= 0)
{
//close(sockfd);
events[i].data.fd = -1;
}
else
{
//buf[n]=' ';
//printf("Socket %d said : %s
",sockfd,buf);
ev.data.fd=sockfd;
ev.events=EPOLLOUT|EPOLLET;
epoll_ctl(epfd,EPOLL_CTL_MOD,connfd,&ev);
}
}
else if( events[i].events&EPOLLOUT )
{
sockfd = events[i].data.fd;
send(sockfd, content.c_str(), content.length(), 0);
ev.data.fd=sockfd;
ev.events=EPOLLIN|EPOLLET;
epoll_ctl(epfd,EPOLL_CTL_MOD,sockfd,&ev);
}
else
{
printf("This is not avaible!");
}
}
}
close(epfd);
return ;
}
void* entranThr(void* arg)
{
printf("create a children thread
");
printThread("children thread");
}
int main()
{
int err = 0;
pthread_attr_t thread_attr;
pthread_attr_init(&thread_attr);
size_t stacksize = 3072 * 1024;
err = pthread_attr_setstacksize(&thread_attr, stacksize);
if(err != 0){
return -1;
}
err = pthread_create(&new_tid, &thread_attr, entranThr, NULL);
pid_t pid;
pthread_t tid;
pid = getpid();
tid = pthread_self();
printf("main thread pid is %lu, tid is %x,new_tid is %x
", (unsigned long)pid, (unsigned long)tid, (unsigned long)new_tid);
while(1) {
sleep(5);
}
return 0;
}