简体   繁体   中英

How to automatically close the process that is started by application, when application closes in c#?

I am getting wired problem with a process that is started by my c# application,in my application i start a process that runs a ffmpeg command which executes well but when in any how if i closes my application then that process still continues to executes.

    private static bool RunRecordProcess(string command)
    {
        Process process = new Process();
        try
        {                
            ProcessStartInfo processStartInfo = new 
            ProcessStartInfo(Application.StartupPath + 
            FFMPEG_EXE_FILE_PATH);
            processStartInfo.UseShellExecute = false;
            processStartInfo.Arguments = "-hide_banner -loglevel 8 " + 
            command;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardInput = true;
            processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            processStartInfo.CreateNoWindow = true;
            processStartInfo.Verb = "";

            process.EnableRaisingEvents = true;
            process.StartInfo = processStartInfo;
            process.Start();               
            string error = process.StandardError.ReadToEnd();
            if (error.Length > 0)
            {
                if (!process.HasExited)
                {
                    process.Kill();
                    //throw new Exception("Failure some error occured");
                }
            }
            process.WaitForExit();
        }   
        catch(Exception ex)
        {
            process.Kill();
            ExceptionHandler.handleException(ex);
            return false;
        }         
        return true;
    }

What i want is when my application exits my process that is started by the application will automatically exit so that no useless process will be using my system Cpu.

Thankyou!

You should create job object (CreateJobObject function in kernel32). There is more description:

https://tulisanlain.blogspot.com/2016/08/kill-child-process-when-parent-exit-c.html

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