今天写一篇非常基础简单的文章,说说网路通讯程序如何体面结束进程释放资源。
开发Linux/mac 这种类unix网络socket通讯程序过程中。我们如何体面结束程序,
释放对应的资源,而不是直接ctrl-c结束进程.
1 使用signal信号,主动捕获SIGINT信号。释放相应的资源.
比如我们之前的Linux音频采集的代码:
//利用m_bRecording = false退出对应的线程,释放资源
void stop_recording()
{
printf("\n signal stop recording...\n");
m_bRecording = false;
return;
}
//程序中注册信号,捕获SIGINT信号.
signal(SIGINT,stop_recording);
2 利用getchar()函数. 比如键盘输入Q,体面退出程序.
void server_running_keyboard_exec()
{
printf("Please Enter 'q' or 'Q' to exit server!\n");
char c;
while(1)
{
usleep(1000*1000);
c = getchar();
printf("%c\n", c);
if(c =='q' || c == 'Q'){
printf("av server exit!\n");
break;
}
else{
if(c != '\n')
printf("enter 'q' or 'Q' to exit server!\n");
continue;
}
}
}
int main(int argc, char* argv[])
{
int ret = create_udp_socket();
if(ret != 0){
printf("create udp socket error...\n");
exit(1);
}
m_bRecvThread = true;
detach_thread_create(NULL,(void*)receive_client_msg_thread,NULL);
server_running_keyboard_exec();
usleep(2000*1000);
p2p_server_stop();
return 0;
}
|