|
一个linux上的支持并发的服务器socket程序,当接收到新的请求之后,就发送字符数组到客户端。两个代码,一个是用了进程,一个是不用进程的,我想请问大家这两个有什么区别吗?万分感谢!!!
/* 有子进程的 */
int main()
{
int i=0,ii,m,n,fd;
unsigned char rreq[10];
pid_t pid;
int sock_fd, client_fd, sin_size;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket is created error!");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port=htons(SERVER_PORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8);
if (bind(sock_fd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == -1)
{
perror("Bind is error");
exit(1);
}
if (listen(sock_fd, BACKLOG) == -1)
{
perror("listen is error");
exit(1);
}
while(1)
{
read(fd,rreq,sizeof(rreq)); // 此段为从spi中读入到rreq字符数组中。
sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sock_fd, (struct sockaddr*)&remote_addr, &sin_size)) == -1)
{
perror("Accept error");
continue;
}
printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr));
pid = fork();
if (pid < 0)
{
perror("Create Process error");
exit(1);
}
else if (pid == 0)
{
if(send(client_fd, rreq, sizeof(rreq), 0) == -1)
{
perror("send is error");
exit(1);
}
close(client_fd);
close(sock_fd);
exit(0);
}
else
{
wait(NULL);
close(client_fd);
}
}
close(sock_fd);
return(0);
}
/* 不带进程的 */
int main()
{
int i=0,ii,m,n,fd;
unsigned char rreq[10];
pid_t pid;
int sock_fd, client_fd, sin_size;
struct sockaddr_in my_addr;
struct sockaddr_in remote_addr;
if ((sock_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
perror("socket is created error!");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port=htons(SERVER_PORT);
my_addr.sin_addr.s_addr = INADDR_ANY;
bzero(&(my_addr.sin_zero), 8);
if (bind(sock_fd, (struct sockaddr*)&my_addr, sizeof(struct sockaddr)) == -1)
{
perror("Bind is error");
exit(1);
}
if (listen(sock_fd, BACKLOG) == -1)
{
perror("listen is error");
exit(1);
}
while(1)
{
read(fd,rreq,sizeof(rreq)); // 此段为从spi中读入到rreq字符数组中。
sin_size = sizeof(struct sockaddr_in);
if ((client_fd = accept(sock_fd, (struct sockaddr*)&remote_addr, &sin_size)) == -1)
{
perror("Accept error");
continue;
}
printf("received a connection from %s\n", inet_ntoa(remote_addr.sin_addr));
/* 有区别的地方, 不创建子进程 */
if(send(client_fd, rreq, sizeof(rreq), 0) == -1)
{
perror("send is error");
exit(1);
}
close(client_fd);
}
close(sock_fd);
return(0);
} |
|