简体   繁体   中英

Can't close process but kill

I have a strange problem.

I've worked for a long time on a project which opens and closes (and if couldn't close, kills) processes which works perfectly on my local machine but which has problems on server.

That piece of code can open and kill processes but always timeouts when closing them.

Following lines does('nt do) the work.

            Parallel.ForEach(Process.GetProcessesByName(applicationName),
            (Process obj) =>
            {
                AddLog("Waiting for " + obj.ProcessName + " to exit at " + DateTime.Now);
                obj.CloseMainWindow();
                obj.WaitForExit(60000);
            });
            System.Threading.Thread.Sleep(1000);
            if (Process.GetProcessesByName(applicationName).Length != 0)
            {
                AddLog("Process couldn't exited. Trying to kill at " + DateTime.Now);
                if ((killable).ToString() == "T")
                {
                    Parallel.ForEach(Process.GetProcessesByName(applicationName),
                    (Process obj) =>
                    {
                        obj.Kill();
                        AddLog(obj.ProcessName + " was killed at " + DateTime.Now);
                        EventLogEntry(obj.ProcessName + " was killed!!!!!", EventLogEntryType.Error, 4003);
                    });
                }
            }

Thanks in advance.

According to the documentation of CloseMainWindow , there is no guarantee that the process will exit upon calling that method. It's possible that the process you're trying to close is displaying a modal dialog. It's also possible that the application which isn't closing does not have a graphical interface (in which case you must use Kill to terminate it). The relevant documentation is provided below.

The request to exit the process by calling CloseMainWindow does not force the application to quit. The application can ask for user verification before quitting, or it can refuse to quit. To force the application to quit, use the Kill method

If CloseMainWindow fails, you can use Kill to terminate the process. Kill is the only way to terminate processes that do not have graphical interfaces.

I noticed that CloseMainWindow returns a bool . You may want to attempt to read that value and only WaitForExit if that was true . You could also try to remote into the server and hook up a debugger to the relevant process to see why it doesn't close.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM