关于socket的接收和发送
写了一个小程序作为一个服务端,大致的作用是当客户端连接时,开线程对客户端发送数据。不知道为什么每次都是数据发送到一半程序自动退出,求各位大大看看
程序如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<pthread.h>
#include<unistd.h>
#include<signal.h>
static int sockfd;
static int ss;
void sig_exit(int signo){
close(sockfd);
printf("exit!\n");
exit(0);
}
void* Pthread_client(void* fd){
int i;
int sfd=*(int*)fd;
char buff[10] = {0};
char buf[1024]={1};
if(read(sfd, buff, sizeof(buf))> 0)
for(i=0; i<ss; i++)
write(sfd ,buf, sizeof(buf));
}
int main(int argc , char* argv[]){
signal(SIGINT,sig_exit);
printf("take Ctrl+C to exit!");
ss=atoi(argv[1]);
//creat socket
sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(sockfd == -1)perror("create socket failed!"),exit(-1);
//address
struct sockaddr_in addr;
addr.sin_family = PF_INET;
addr.sin_port = htons(7000);
addr.sin_addr.s_addr = INADDR_ANY;
//bind
int ret=bind(sockfd,(struct sockaddr*)&addr,sizeof(addr));
if(ret == -1)perror("bind error!"),exit(-1);
//listen
if(listen(sockfd, 100) == -1)
perror("listen error!"),exit(-1);
//wait client
while(1){
struct sockaddr_in fromaddr;
socklen_t len = sizeof(fromaddr);
int fd = accept(sockfd, (struct sockaddr*)&fromaddr,&len);
if(fd == -1)perror("accept error!"),exit(-1);
pthread_t id;
pthread_create(&id,0,Pthread_client,(void*)&fd);
}
pause();
return 0;
}
[解决办法]
先屏蔽掉SIGPIPE信号。