2

I am crating SSL socket and when I try to connect to that socket my program hangs.

I found some issue that server does not send any data so SSL connection is waiting for the any response.

I decided to create future and kill it after timeout. But it is still hanging.

If you see to the code, below part is not executed: cout<<"TEST";

{

     std::future<void> future = std::async(std::launch::async, 
     [&](){ 
              err = SSL_connect (m_ssl); 
          });

     std::future_status status;
     status = future.wait_for(std::chrono::seconds(t_timeout));
}

cout<<"TEST";

To simulate stopping response from server I just run:

for item in $(seq 1 1000); do sudo nc -i 100000ms -l 443 >> log.out; done;

How do I kill the SSL connection? I want to continue execution of code after kill the future.

EDIT: I do not want to open another question for that. Answer: So i am sure now that this is because of future destructor. It is waiting for finish of code from the future body.

Question 2: How Can I fix above issue? I want to execute code after scope which future is in.

Is it OK to create thread and wait until timeout or ssl some mutex is unlocked?

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36
Daniel Hornik
  • 1,957
  • 1
  • 14
  • 33
  • Have you actually checked the value of `t_timeout`? – Davide Spataro Jul 31 '19 at 12:49
  • Yes its 3 seconds and future is exiting when I do debug with gdb its exiting from scope and it stopping execution(hangs) before `cout<<"TEST";` – Daniel Hornik Jul 31 '19 at 12:51
  • 1
    If `SSL_connect` blocks indefinitely and does not return then neither threads or async code will help to get around it. There is no such thing as "killing" future. – user7860670 Jul 31 '19 at 13:17
  • @VTT What can help me? Manual create and kill the thread? – Daniel Hornik Jul 31 '19 at 13:19
  • 1
    "Forever blocking" functions are broken by design, there is no way around it. At most you will be left with leaking blocked threads. Switching to some proper library / API could help. – user7860670 Jul 31 '19 at 13:21

1 Answers1

3

The problem with your code is that when the future goes out of scope, its destructor might block as reported in the documentation for std::future<T>::~future:

It says explicitly:

... will not block for the shared state to become ready, except that it may block if all of the following are true: the shared state was created by a call to std::async, the shared state is not yet ready, and this was the last reference to the shared state.

In your case:

  1. the shared state is not yet ready: SSL hangs forever
  2. that is the only (and so last) reference to the shared state.

The solution to your problem is that you have to make the scope of variable std::future<void> future such that it outlives the part of the code you want not to be blocked.

Check these answers:

LIVE DEMO

Davide Spataro
  • 7,319
  • 1
  • 24
  • 36