强制终端关闭后关闭套接字

强制终端关闭后关闭套接字

我正在运行蓝牙套接字服务器,该服务器正在侦听传入连接。但我强制终端关闭 ctrl + Z 。之后服务器不再列出并显示输出accepted connection from 00:00:00:00:00:00

要使其再次运行,我应该重新启动计算机。如何正确关闭套接字以便无需重新启动即可再次运行服务器

int main(int argc, char **argv)
{
    struct sockaddr_rc loc_addr = { 0 }, rem_addr = { 0 };
    char buf[1024] = { 0 };
    int s, client, bytes_read;
    socklen_t opt = sizeof(rem_addr);
    s = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
    loc_addr.rc_family = AF_BLUETOOTH;
    loc_addr.rc_bdaddr = *BDADDR_ANY;
    loc_addr.rc_channel = (uint8_t) 1;
    bind(s, (struct sockaddr *)&loc_addr, sizeof(loc_addr));
    listen(s, 1);
    client = accept(s, (struct sockaddr *)&rem_addr, &opt);
    ba2str( &rem_addr.rc_bdaddr, buf );
    fprintf(stderr, "accepted connection from %s\n", buf);
    memset(buf, 0, sizeof(buf));
    bytes_read = read(client, buf, sizeof(buf));
    if( bytes_read > 0 ) {
        printf("received [%s]\n", buf);
    }
    close(client);
    close(s);
    return 0;
}

相关内容