Let's first briefly understand the basic functions of the curl_multi_* series:
curl_multi_init(): Initializes a multi-handle for managing multiple cURL handles.
curl_multi_add_handle(): Adds a cURL handle to the multi-handle.
curl_multi_remove_handle(): Removes a cURL handle from the multi-handle.
curl_multi_exec(): Executes all the requests added to the multi-handle.
curl_multi_close(): Closes the multi-handle and cleans up resources.
curl_close(): Closes a single cURL session handle and releases all resources associated with that handle.
curl_multi_remove_handle(): Removes a cURL handle from the multi-handle, but does not directly close the cURL session. After removal, the handle remains valid and can still be used or closed elsewhere.
We need to clarify two points:
curl_multi_remove_handle() operates on the multi-handle, not the session. Calling this function does not terminate the request or release resources associated with the cURL session.
curl_close() releases resources. When we call curl_close(), the associated cURL handle is destroyed. Therefore, we don't want to destroy the handle before removing it.
Based on these characteristics, let's analyze the call sequence:
This is the recommended sequence. Because:
When you remove the cURL handle, it detaches from the multi-handle but does not close the session. You can perform additional actions on the handle afterward (such as logging or debugging).
If you call curl_close() first, the session will be closed directly, and you won't be able to operate on the handle afterward.
This sequence is incorrect because:
Once you call curl_close(), the cURL session is destroyed and its resources are released. You won't be able to remove the handle from the multi-handle.
Even if you attempt to remove the session from the multi-handle, cURL may have already released the resources internally, leading to unexpected errors.
Therefore, this sequence can cause crashes or undefined behavior.
A standard flow should be:
Use curl_multi_add_handle() to add each cURL session to the multi-handle.
Call curl_multi_exec() to execute and wait for responses.
Use curl_multi_remove_handle() to remove completed or no longer needed cURL sessions from the multi-handle.
Finally, call curl_close() to close each cURL session and release associated resources.
Call curl_multi_close() to close the multi-handle and release associated resources.
curl_multi_remove_handle() should be called before curl_close(). Calling curl_multi_remove_handle() only removes the cURL session from the multi-handle and does not release resources. Therefore, after removing the handle, you can still close the cURL session and free the resources. Be sure to avoid calling curl_close() first, as it will cause an error when removing the handle.