为了成为自由自在的人而奋斗!
分类: 系统运维
2010-10-26 09:23:49
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXSIZE (4096)
void pthread_proc(int *peer_ptr)
{
char recvmsg[MAXSIZE], sendmsg[MAXSIZE];
int peer = *peer_ptr;
while (1) {
memset(recvmsg, 0, MAXSIZE);
memset(sendmsg, 0, MAXSIZE);
if (read(peer, recvmsg, sizeof(recvmsg)) < 0) {
perror("recv err");
break;
}
printf("client: %s\n", recvmsg);
if (!strcmp(recvmsg, "quit")) {
printf("close a connection\n\n");
break;
}
strcpy(sendmsg, recvmsg);
strcat(sendmsg, " send back");
write(peer, sendmsg, strlen(sendmsg));
}
close(peer);
return;
}
int main(int argc, char *argv[])
{
int sockfd, peer, len, ready;
fd_set fds;
struct sockaddr_un serv_addr;
pthread_t phd;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("socket error");
return -1;
}
serv_addr.sun_family = AF_UNIX;
strcpy((char *)serv_addr.sun_path, "e:\\sockfile");
unlink("e:\\sockfile");
if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) {
perror("bind err");
return -1;
}
if (listen(sockfd, 1) < 0) {
perror("listen error");
close(sockfd);
return -1;
}
len = sizeof(serv_addr);
while (1) {
printf("begin to accept\n");
FD_ZERO(&fds);
FD_SET(sockfd, &fds);
ready = select(sockfd + 1, &fds, 0, 0, NULL);
if (ready > 0 && FD_ISSET(sockfd, &fds)) {
peer = accept(sockfd, (struct sockaddr *)&serv_addr, &len);
if (peer < 0) {
perror("Server: accept failed.\n");
close(sockfd);
return -1;
}
if (pthread_create(&phd, NULL, (void *)pthread_proc, (void *)&peer) != 0) {
close(peer);
}
}
}
return 0;
}
支持多线程处理