问题
This general topic has come up before, here, here, here, and no doubt elsewhere on the internet as well. In my case, unlike these, the hang arises from a blocking socket that never gets a message, and perhaps that's why the solutions described there haven't worked for me. I'm developing in tandem a C++ app which communicates with the php script via a local socket connection, and when the C++ app crashes, it leaves the php script's socket waiting for a message that never comes. I've tried using session_destroy and session_unset (calling these first in a script before session_start) but they don't work; even quitting and restarting the browser doesn't help. I can only stop the session if I remove the session_start, reload the script and then end the session via the client. How can I kill the session without having to go through that?
Edit: I forget to mention, I also tried to time the socket out with
socket_set_option($socket,0, SO_RCVTIMEO, array("sec"=>1, "usec"=>0));
But I got an 'invalid operation' error, and it didn't work.
Edit 2: Setting a manual timeout, following the tip here, worked well enough. I still don't know how to, in general, kill a session that's e.g. stuck in an infinite loop, but oh well.
回答1:
Maybe you can give a timeout to the socket? e.g. socket_select has a timeout parameter.
The value of 1000s
as timeout may be too high, because apache may have killed the process before (see max_execution_time
in php.ini
)
回答2:
How can I kill the session without having to go through that?
The problem you're having isn't one that will be solved by killing the session.
the hang arises from a blocking socket that never gets a message
If you're using the default PHP session handler, that means that PHP is holding a lock on that file. No other PHP process is going to be able to manipulate the session as long as that lock exists.
You have a few options here.
First, consider implementing you own session save routines, which means you'd completely control whether or not there is any sort of lock on the session data. You can simply not include any locking at all, which will permit the running-but-hung PHP script to continue running in peaceful bliss. This is the most complex option.
Second, are you sure that the long-running socket script needs to write session data? If not, you can simply end the session early and release the lock by calling session_write_close. This will release the lock, though it won't actually end the long-running script when the socket closes.
Third, look at using socket timeouts in your long-running script. I'm not sure what exact method you're using to work with sockets here and have very little experience working with them in PHP, so I can't make a specific function recommendation.
来源:https://stackoverflow.com/questions/5771478/how-to-kill-a-php-session