简体   繁体   English

C信号(替代?)用于多线程

[英]C signal (alternative ?) for multi-threading

I'm sending an array of floats, one by one, over a TCP socket . 我通过TCP套接字一个接一个地发送一个浮点数组。 My Server (receiver - which handles multiple requests simultaneously) program should read data until until receiving the value 0. If the client(sender) doesn't send anything for 10 seconds after he connected (or after the last sent value) i want the server to close that connection. 我的服务器(接收器 - 同时处理多个请求)程序应该读取数据,直到收到值0.如果客户端(发送者)在连接后(或在最后发送的值之后)10秒内没有发送任何内容,我希望服务器关闭该连接。 I found this signal approach but I think it will not be optimal to use in threads, but more likely for fork() because it forces me to use global variables. 我发现了这种信号方法,但我认为在线程中使用它不是最佳的,但更可能是fork(),因为它迫使我使用全局变量。 I must send the "socket" param to the function, so i can close it and AFAIK this is not posible. 我必须将“socket”参数发送到函数,所以我可以关闭它,而AFAIK这是不可能的。

void time_out(int semnal) {
  printf("Time out.\n");
  close(socket);
  exit(1);
}

and each time a client has connected, or sends something, I call this: 每次客户端连接或发送内容时,我都称之为:

signal(SIGALRM, time_out);
alarm(10);

What other options do i have to count 10 seconds and to be able to restart this timer? 还有什么其他选项可以计算10秒并且能够重新启动此计时器?

You could use select with an empty FD set and a timeout. 您可以使用带有空FD设置和超时的select。 That's pretty common and pretty portable. 这很常见且很便携。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM