/*
實現將字符加密,顛倒返回
*/
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
const char * end;
#define MAX 100
#define PORT 34561
#define LAN 8
#define OPEN_LINKER 56
void err_quit(const char *s)
{
syslog(LOG_INFO|LOG_LOCAL3,"%s", s);
exit(0);
}
void SyslogInfor(const char * s)
{
syslog(LOG_INFO|LOG_LOCAL3,"%s", s);
return ;
}
void err_child_progress(const int status)
{
char buff[MAX];
if(WIFEXITED(status))
{
err_quit("其終止狀態是按照正常終止的\n");
return;
}
else if(WIFSIGNALED(status))
{
snprintf(buff, MAX, "異常終止,其異常終止的ID是%d\n",WTERMSIG(status));
err_quit(buff);
return;
}
else if(WIFSTOPPED(status))
{
snprintf(buff, MAX, "當前暫停子進程,且子進程id是%d\n",WSTOPSIG(status));
err_quit(buff);
return ;
}
}
int Socket(const int AF,const int SO,const int a)
{
int sockfd;
sockfd=socket(AF,SO,a);
if(sockfd==-1)
err_quit("socket error!");
return sockfd;
}
int Bind(const int Sockfd,const struct sockaddr *server,socklen_t len)
{
int bin;
bin=bind(Sockfd, server, len);
if(bin==-1)
err_quit("bind error!");
return bin;
}
int Listen(const int sockfd,const int lan)
{
int listened;
listened=listen(sockfd, lan);
if(listened==-1)
err_quit("listen error");
return listened;
}
void guard_structure(const char *panem,int facility)
{
pid_t pid;
if((pid==fork())>0)
_exit(0);
else if(pid<0)
err_quit("創建進程失敗!\n");
if(setsid()<0)
err_quit("創建session leader失敗\n");
signal(SIGHUP, SIG_IGN);
//忽略信號
/*
這裏你還要考慮一下就是一個問題,如果你在打開一個終端的話依然可能造成其終止進程
*/
if((pid=fork())>0)
_exit(0);
else if(pid<0)
err_quit("二次守護進程失敗!\n");
//改變工作的路徑到根目錄下
chdir("/");
umask(0);
/*
關閉文件描述符,防止有描述符的佔用
*/
for(int i=0;i0);
err_child_progress(status);
return ;
}
void ControlingStringsTCP(const int con)
{
/*
防止服務器主機出現sigpipe信號的出現,造成服務器關閉,我們的設計就應該考慮的是用select函數防止服務器關閉出現。
這樣的情況是:一個進程向一個已收到RST的套接字上執行寫操作內核就會發送一個sigpipe信號,終止信號。其捕獲後應該做的是不加任何處理signal(sigpipe,sig_ign);返回的errno==EPiPE的
*/
char sen[MAX],rec[MAX];
int num,i,j;
memset(sen, 0, MAX);
memset(rec,0,MAX);
while((num=(int)read(con, rec, MAX))>0)
{
rec[num]='\0';
if(num>MAX)
return ;
j=strlen(rec);
for(int k=0;k='a'&&rec[k]<='z')||(rec[k]>='A'&&rec[k]<='Z'))
{
rec[k]+=4;
if((rec[k]>'Z'&&rec[k]<='Z'+4)||(rec[k]>'z'))
rec[k]-=4;
}
}
rec[j]='\0';
for(i=0;i0)
{
snprintf(buf, MAX, "from the client:%s:%d\n",inet_ntoa(client.sin_addr),ntohs(client.sin_port));
SyslogInfor(buf);
}
pid=fork();
if(pid==0)
{
close(sockfd);
ControlingStringsTCP(con);
exit(0);
}
close(con);
}
return 0;
}
守護進程實現,unix網絡編程學習讓自己更美好!
MAC OS 配置守護進程:gcc 編譯後 ,使用sudo 命令,用ps -ejf 查看進程id,進程其父進程爲1(init進程);