02-01-2025 09:28 PM
I have an event structure handling (and discarding) the "Application Instance Close?". The code in the event case starts a shutdown of my code that may or may not succeed in an indeterminate amount of time.
I started handling this event mainly because it is triggered by an OS shutdown/restart. I later discovered that taskkill triggers it if you don't use the /F option. This absolutely delighted me because it gave me a scriptable way to safely attempt to close my program without having to put in any networking hooks.
For some reason taskkill isn't working in a particular situation I've run into (running via psexec) so I'm trying to find alternatives. The only other way to trigger the event I've found is with .NET's CloseMainWindow.
What else can cause this event to fire? I've to use python's psutil but couldn't find a way to do it with that.
Also if anyone has thoughts about why taskkill isn't working over psexec I'd love to hear them (I imagine it's because the sessions are different but I don't have a good way to deal with that).
02-02-2025 01:47 AM
@avogadro5 wrote:What else can cause this event to fire? I've to use python's psutil but couldn't find a way to do it with that.
Also if anyone has thoughts about why taskkill isn't working over psexec I'd love to hear them (I imagine it's because the sessions are different but I don't have a good way to deal with that).
Some time ago, I implemented the same, and after several reports of "sometimes it works, sometimes it doesn't without any reason and sporadically", I decided to have my own "shutdown" channel fully independent from the OS signal. I mean I'm still using Application Instance Close? for overall OS shutdown (it works), but when I need to shut down my app from a third-party app, I do something like this:
Then the shutdown script, for example in Python, will be more than a single line, but not very complicated:
import socket
# Define the app server address and port
app_address = 'localhost'
app_port = 1234
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to the app
sock.connect((app_address, app_port))
print(f"Connected to {app_address}:{app_port}")
# Send the "SHUTDOWN" message
message = "SHUTDOWN"
sock.sendall(message.encode())
print(f"Sent: {message}")
finally:
# Close the socket
sock.close()
print("Connection closed.")
The channel is different, depending on the design. For example, if I need programmatic shutdown from a PLC, then it is done via OPC UA with one bit; shutdown initiated from cRIO may be done via shared variable, etc.
Yes, this is additional "overhead", but at least it works like a charm, also over network, because there's no OS dependency.
02-03-2025 01:55 PM
The workaround I have implemented is to call taskkill via a scheduled task, which can be specified to use an interactive session.