我有一个 C 程序,它使用 libwebsockets
打开从客户端到服务器的 websocket。但是,有时网络可能会出现故障。在这种情况下,我在下面编写了一些逻辑,尝试连接 10 次,如果不成功,则应该退出应用程序。逻辑按预期工作,但看起来不太整洁,我确信有更好的方法来做到这一点。对于如何更好地编写此逻辑的评论,我将不胜感激。 exit(-1)
也是退出的正确方法吗?
//Try connect to websocket 10 times or else exit app
for (int j =0; j < 10; j++) {
web_socket = lws_client_connect_via_info ( &ccinfo);
//If you get a connection then exit the for loop
if(web_socket){
break;
}
}
//If you tried 10 times web_socket will be NULL so exit the application
if(!web_socket) {
exit(-1);
}
最佳答案
exit来自 stdlib.h
是最好的方法。从标准开始
Terminates the process normally, performing the regular cleanup for terminating processes.
First, all functions registered by calls to atexit are executed in the reverse order of their registration. Then, all streams are closed and the temporary files deleted, and finally the control is returned to the host environment.
The status argument is returned to the host environment.
我认为代码逻辑很简单,每个人都可以理解。
“我们应该忘记小效率,大约 97% 的情况下:过早的优化是万恶之源。” - Donald E. Knuth
关于c - 如果无法获得 websocket 连接则退出应用程序的逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45664728/