gpt4 book ai didi

发生自定义错误时关闭服务器(套接字)

转载 作者:行者123 更新时间:2023-11-30 17:15:23 24 4
gpt4 key购买 nike

我正在使用 C 套接字编写一个简单的客户端服务器程序。我使用了 http://www.tutorialspoint.com/unix_sockets/socket_server_example.htm 中的代码现在我正在尝试扩展代码,即当我有多个客户端时,我检查我的 doprocessing 函数中是否发生自定义错误,如果是这种情况,我想停止服务器,但我不知道如何?

// Setup socket, works
for(;;) {
ConnectFD = accept(SocketFD, (struct sockaddr*) &cli_addr, (socklen_t*)&clilen);

if (pid == -1) {
perror("Error: Fork");
close(SocketFD);
exit(EXIT_FAILURE);
}

if (pid == 0) {
close(SocketFD);
error = doprocessing(ConnectFD);
if (error == 1) {
// Stop the server
}
exit(EXIT_SUCCESS);
} else {
close(ConnectFD);
}
}
return 0;

所以我检查错误,如果错误为 1,我想关闭服务器,但我真的不知道该怎么做。

最好的成绩

最佳答案

有点不清楚你在这里问什么。如果您只想关闭处理错误请求的子服务器,则只需让它调用 exit():

if (pid == 0) {
close(SocketFD);
error = doprocessing(ConnectFD);
if (error == 1) {
// Stop the server
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);

但我怀疑您知道这一点,也许您是说您希望它关闭子服务器的父服务器?如果是这样,并且您使用的是 UNIX/Linux 类型系统,则可以使用 getppid(2) 系统调用获取父进程的进程 ID,然后向其发送 SIGTERM信号告诉它关闭。例如:

if (pid == 0) {
close(SocketFD);
error = doprocessing(ConnectFD);
if (error == 1) {
/* Find the parent server */
pid_t parent = getppid();
/* Stop the parent server */
kill(parent, SIGTERM);
/* And stop the child */
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);

关于发生自定义错误时关闭服务器(套接字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30004760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com