这个程序为什么会出现段错误呢?
[root@wengzhong linux]# ./server.exe
段错误
[root@wengzhong linux]#
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<sys/socket.h>
#include<sys/wait.h>
#include<string.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#define MYPORT 4000
#define BACKLOG 10
int main()
{
int sockfd,new_fd;
struct sockaddr_in my_addr,their_addr;
int sin_size;
//取得文件描述符
if((sockfd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
fprintf(stderr,"socket error\n");
}
else
{ //初始话参数
my_addr.sin_family= AF_INET;
my_addr.sin_port = htons(MYPORT);
my_addr.sin_addr.s_addr=inet_addr(INADDR_ANY);
bzero(&(my_addr.sin_zero),8);
//帮定
if(bind(sockfd,(struct sockaddr*)&my_addr,sizeof(struct sockaddr))==-1)
{
fprintf(stderr,"bind error\n");
exit(EXIT_FAILURE);
}
//监听
if(listen(sockfd,BACKLOG)==-1)
{
fprintf(stderr,"listen error\n");
exit(EXIT_FAILURE);
}
while(1)
{
sin_size=sizeof(struct sockaddr_in);
if((new_fd=accept(sockfd,(struct sockaddr *)&their_addr,(socklen_t *)&sin_size))==-1)
{
fprintf(stderr,"accept error");
continue;
}
printf("server : got connection from %s\n",inet_ntoa(their_addr.sin_addr));
if(!fork())
{
//如果是子程序发送
if(send(new_fd,"hello,word!\n",15,0)==-1)
{
fprintf(stderr,"send error\n");
}
close(new_fd);
exit(0);
}
close(new_fd);
while(waitpid(-1,NULL,WNOHANG)>0);
}
}
}