socket文件傳輸-發送端
接收端:https://blog.csdn.net/qq_33904382/article/details/104827718
C,使用socket傳輸文件的服務端;主函數也可作爲一般服務程序的基本框架。
主程序:
/*
author:hhy
time: 2020/3/7
*/
/* Basic IO */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
/* structure */
#include<arpa/inet.h>
#include<netinet/in.h>
/* socket */
#include<sys/socket.h>
/* signal */
#include<signal.h>
#include<errno.h>
typedef struct sockaddr SA;
const int maxsize=1024;
void child_do(int connectsock); /* real reaction of son-process for clients' requests */
void sig_chld(int signo);/* sig dealing function ,for SIGCHLD */
int main()
{
//Create Socket
int ListeningSocket = socket(AF_INET,SOCK_STREAM,0);
//Init Address Structure
struct sockaddr_in ListenAddrStrc,ConnectedAddrStrc;
memset(&ListenAddrStrc,0,sizeof(ListenAddrStrc));
ListenAddrStrc.sin_family = AF_INET;
ListenAddrStrc.sin_addr.s_addr = htonl(INADDR_ANY);
ListenAddrStrc.sin_port = htons(13000);
//Bind Socket and Address
bind(ListeningSocket,(SA*)&ListenAddrStrc,sizeof(ListenAddrStrc));
//Listen to the Listening Socket
listen(ListeningSocket,5);
signal(SIGCHLD,sig_chld);/* for fork(),catching SIGCHLD signal */
//Listening and Accpet、Reply
for(;;){
//Accpet client's asking
socklen_t clilen = sizeof(ConnectedAddrStrc);
int ConnectedSocket = accept(ListeningSocket,(SA*)&ConnectedAddrStrc,&clilen);
//deal with interruption of slow systen call accept()>
if(ConnectedSocket<0){
if(errno == EINTR)/* be interrupted by sig dealing func */
continue;/* retry,restart accept() again */
else{ /* other errno . */
fprintf(stderr,"errno:wrong of accept()");
exit(0);
}
}
//What children does
int child_pid;
if((child_pid=fork())==0){
close(ListeningSocket);/* close listeningsocket in child process */
child_do(ConnectedSocket);
exit(0);
}
close(ConnectedSocket);
}
return 0;
}
child_do: 子進程執行實際任務(答覆以指定文件給發起請求的client端)
void child_do(int connectsocket)
{
/* trans file to */
int n;
char buffer[maxsize];
memset(buffer,0,maxsize);/* Init the buffer */
int srcfile = open("./TransSender.c",O_RDONLY);
while((n = read(srcfile,buffer,maxsize))>0){
write(connectsocket,buffer,n);
}
}
sig_chld: 子進程SIGCHLD信號處理函數
void sig_chld(int signo)
{
pid_t pid;/* identify number of son-process */
int stat;/* return end status of the son-process */
while((pid=(waitpid(-1,&stat,WNOHANG))));/* arg WNOHANG means don't hang when sth is running */
}