#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/socket.h>
#include<string.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/wait.h>
#define PORT 8900
#define BUFSIZE 2048
int execute(char*recv,char*buf)
{
char *command[4] = {"sh","-c",NULL,NULL};
int pipe_fd[2];
pid_t pid;
command[2] = recv;
if(-1== pipe(pipe_fd))
{
perror("pipe creat error\n");
return 1;
}
pid = fork();
if(-1==pid)
{
perror("fail to fork\n");
exit(1);
}
else if(pid ==0)
{
close(pipe_fd[0]);
dup2(pipe_fd[1],STDOUT_FILENO);
execvp("sh",command);
memset(buf,0,2047);
write(pipe_fd[1],buf,2047);
close(pipe_fd[1]);
_exit(1);
}
else
{
close(pipe_fd[1]);
waitpid(pid,NULL,0);
read(pipe_fd[0],buf,2047);
buf[2047]='\0';
close(pipe_fd[0]);
}
return 0;
}
int main()
{
int sockfd;
int conn_sock;
char sendbuf[BUFSIZE];
char recvbuf[BUFSIZE];
int sendnum;
int recvnum;
int length;
struct sockaddr_in client;
struct sockaddr_in server;
int opt;
int cnt;
pid_t pid;
/* The first stage:INITILIZE */
memset(&client,0,sizeof(client));
memset(&server,0,sizeof(server));
memset(sendbuf,0,BUFSIZE);
memset(recvbuf,0,BUFSIZE);
length=0;
sockfd=-1;
conn_sock=-1;
opt=SO_REUSEADDR;
/*The second stage:create listen socket */
if (-1==(sockfd=socket(AF_INET,SOCK_STREAM,0)))
{
perror("create socket error\n");
return -1;
}
setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&opt,sizeof(opt));
/* The third stage:bind socket */
server.sin_family=AF_INET;
server.sin_addr.s_addr=htonl(INADDR_ANY);
server.sin_port=htons(PORT);
if (-1==bind(sockfd,(struct sockaddr*)&server,sizeof(server)))
{
perror("bind socket error\n");
close(sockfd);
return -1;
}
/* The fourth stage:listen socket */
if (-1==listen(sockfd,10))
{
perror("listen socket error\n");
close(sockfd);
return -1;
}
/* The fifth stage:creat connect socket */
while(1)
{
if (-1==(conn_sock=accept(sockfd,(struct sockaddr*)&client,&length)))
{
perror("three shakehands error\n");
close(sockfd);
return -1;
}
/* the commnication with client */
pid = fork();
if(-1 == pid)
{
perror("fork error\n");
exit(1);
}
else if(0 == pid)
{
close(sockfd);
while(1)
{
memset(recvbuf,0,BUFSIZE);
memset(sendbuf,0,BUFSIZE);
if (0>=(recvnum=read(conn_sock,recvbuf,BUFSIZE)))
{
perror("the commucation error\n");
close(conn_sock);
return -1;
}
recvbuf[recvnum]='\0';
fprintf(stderr,"the command is:%s\n",recvbuf);
if (0==strcmp(recvbuf,"quit"))
{
fprintf(stderr,"the client is quit\n");
close(conn_sock);
break;
}
if (0!=execute(recvbuf,sendbuf))
{
sprintf(sendbuf,"the invalid command,please try again\n");
}
fprintf(stderr,"the result is \n%s",sendbuf);
if (0>=(sendnum=write(conn_sock,sendbuf,strlen(sendbuf))))
{
perror("the commucation error\n");
close(conn_sock);
_exit(1);
}
}
_exit(0);
}
else
{
waitpid(pid,NULL,WNOHANG);
continue;
}
}
}
评论0