Home > Backend Development > C++ > How to Ensure Child Processes Terminate When the Parent Application Crashes in C#?

How to Ensure Child Processes Terminate When the Parent Application Crashes in C#?

Susan Sarandon
Release: 2025-01-25 04:45:10
Original
269 people have browsed it

How to Ensure Child Processes Terminate When the Parent Application Crashes in C#?

In the C#, the mechanism of implementing the child process with the end of the father

When using the class creation process, it is important to ensure that the child process is also endless when the parent application crash. However, in some cases, for example, when the application is terminated through the task manager, this behavior is not automatically realized.

In order to solve this problem, we can use the "operating object" provided by the Windows operating system. By creating an assignment object for the parent and registering the sub -processes, we can establish a dependency relationship between processes. This ensures that when the father's process is terminated, the operating system will automatically terminate the child process. System.Diagnostics.Process

The implementation of the operating object

The following code demonstrates how to create the operating object and associate the process with it:

The key line in the constructor is:

<code class="language-csharp">public class Job : IDisposable
{
    private IntPtr m_handle;
    private bool m_disposed = false;

    public Job()
    {
        m_handle = CreateJobObject(IntPtr.Zero, null); // 修正:使用IntPtr.Zero

        JOBOBJECT_BASIC_LIMIT_INFORMATION info = new JOBOBJECT_BASIC_LIMIT_INFORMATION();
        info.LimitFlags = 0x2000; // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE

        JOBOBJECT_EXTENDED_LIMIT_INFORMATION extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
        extendedInfo.BasicLimitInformation = info;

        int length = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
        IntPtr extendedInfoPtr = Marshal.AllocHGlobal(length);
        Marshal.StructureToPtr(extendedInfo, extendedInfoPtr, false);

        if (!SetInformationJobObject(m_handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length))
            throw new Exception($"无法设置信息。错误代码:{Marshal.GetLastWin32Error()}"); // 使用插值字符串

        Marshal.FreeHGlobal(extendedInfoPtr); // 释放非托管内存
    }

    public bool AddProcess(IntPtr handle)
    {
        return AssignProcessToJobObject(m_handle, handle);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    protected virtual void Dispose(bool disposing)
    {
        if (m_disposed)
            return;

        if (disposing) { }

        Close();
        m_disposed = true;
    }

    public void Close()
    {
        Win32.CloseHandle(m_handle);
        m_handle = IntPtr.Zero;
    }
}</code>
Copy after login
This sets the logo, which specifies that when the operation is closed, all processes associated with the job should be terminated.

After creating a job object, you can use the
<code class="language-csharp">info.LimitFlags = 0x2000;</code>
Copy after login
method to connect the child process. Examples as follows:

JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE By registering the sub -process to the operating object, they can ensure that they will end automatically even if the operating system suddenly terminates. The code is added with error processing and resource release, which improves the robustness and reliability of the code. At the same time, the Excel interoperability library is made correctly.

Note: AddProcess This method depends on the operating object function provided by the Windows operating system, which is only applicable to the Windows platform. In addition, you need to add the

<code class="language-csharp">using Microsoft.Office.Interop.Excel; // 确保引用了Excel互操作库

// ...其他代码...

Excel.Application app = new Excel.ApplicationClass();

uint pid = 0;
Win32.GetWindowThreadProcessId(new IntPtr(app.Hwnd), out pid);
Process process = Process.GetProcessById((int)pid);
job.AddProcess(process.Handle);

// ...其他代码...

// 记得释放COM对象
Marshal.ReleaseComObject(app);
app = null;

// ...其他代码...</code>
Copy after login
statement (

class) of the , and this part is omitted in the code, you need to add it by yourself. And it is necessary to deal with potential abnormalities, such as no process or insufficient permissions. Finally, remember to release the COM object to avoid the leakage of resources.

The above is the detailed content of How to Ensure Child Processes Terminate When the Parent Application Crashes in C#?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template