0

I am running a script that launches a program via cmd and then, while the program is open, checks the log file of the program for errors. If any, close the program.

I cannot use taskkill command since I don't know the PID of the process and the image is the same as other processes that I don't want to kill.

Here is a code example:

import os, multiprocessing, time

def runprocess():
    os.system('"notepad.exe"')

if __name__ == '__main__':
    process = multiprocessing.Process(target=runprocess,args=[])
    process.start()
    time.sleep(5)

    #Continuously checking if errors in log file here...
    process_has_errors = True #We suppose an error has been found for our case.

    if process_has_errors:
        process.terminate()

The problem is that I want the notepad windows to close. It seems like the terminate() method will simply disconnect the process without closing all it's tasks.

What can I do to make sure to end all pending tasks in a process when terminating it, instead of simply disconnecting the process from those tasks?

2 Answers 2

1

You can use taskkill but you have to use the /T (and maybe /F) switch so all child processes of the cmd process are killed too. You get the process id of the cmd task via process.pid.

Sign up to request clarification or add additional context in comments.

1 Comment

That's it. I also must say that I found the way to find the process PID, by using pid = process.pid in my code. Then, this pid is added to a command looking like os.system('"taskkill /pid ' + str(pid) + ' /F /T"')
0

You could use a system call if you know the name of the process:

import os
...
    if process_has_errors:
        processName = "notepad.exe"
        process.terminate()
        os.system(f"TASKKILL /F /IM {processName}")

2 Comments

Sorry, I cannot use the image of the process since there are other processes that I don't want to close with the same image. But I definitely believe this will help others that doesn't have this constraint.
Im sorry that i was not able to help you but Im glad you found a solution!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.