实验要求
修改远程控制服务器代码,使得服务器同时能够向多个用户提供服务。消除僵尸进程,收回所有子进程资源。
实验环境
Red Hat 9
代码
server.c
#include<stdio.h>
#include<unistd.h>
#include<sys/socket.h>
#include<string.h>
#include<netdb.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<sys/socket.h>
#define PORT 8900
#define BUF_SIZE 2048
int execute(char* command,char* buf);
int main()
{
int sockfd;
struct sockaddr_in client;
struct sockaddr_in server;
char send_buf[BUF_SIZE];
char recv_buf[BUF_SIZE];
char cmd[2048];
int sendnum;
int recvnum;
int length;
int port;
int connected; //change
memset(send_buf,0,2048);
memset(recv_buf,0,2048);
memset(cmd,0,2048); //change
port = PORT;
if (-1==(sockfd=socket(AF_INET,SOCK_STREAM,0))) //change
{
perror("generating socket error\n");
exit(1);
}
memset(&server,0,sizeof(struct sockaddr_in));
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(struct sockaddr)))
{
perror("binding error\n");
close(sockfd);
exit(1);
}
if(-1==listen(sockfd,10))
{
perror("listen socket error\n");
close(sockfd);
return -1;
}
length = sizeof(struct sockaddr_in);
while(1)
{
memset(recv_buf,0,2048);
memset(send_buf,0,2048);
if(-1==(connected=accept(sockfd,(struct sockaddr*)&client,&length)))
{
perror("three shakehands error\n");
close(sockfd);
return -1;
}
//change///
int pid = fork();
if((pid=fork())<0)
{
printf("fork failed\n");
_exit(1);
}
else if(pid == 0)
{
//close(connected);
process(connected, client);
}
else
{
close(connected);
continue;
}
close(connected);
}
close(sockfd);
exit(1);
}
int process(int connected, struct sockaddr_in client)
{
char sendbuf[BUF_SIZE];
char recvbuf[BUF_SIZE];
int sendnum = 0;
int recvnum = 0;
int cnt;
int n, fd[