2

So I'm building a .NET core 3.1 app and I am opening a few processes, I want to keep track of them and kill them when I click certain buttons, however.. I was reading that killing a process based on an ID was not a good idea.

So I found this SO post about it

https://stackoverflow.com/a/2316683/11966121

and it was explaining how to do it, but that uses the kernel32 dll which doesnt exist in Linux, so what can I do to convert it?

I essentially want to do this, but in Linux.

class Job
{
    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    public static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName);

    [DllImport("kernel32.dll")]
    public static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);

    [DllImport("kernel32.dll")]
    public static extern bool TerminateJobObject(IntPtr hJob, uint uExitCode);

    IntPtr job;

    public Process StartProc(string commandLine)
    {
        if (job == IntPtr.Zero)
            job = CreateJobObject(IntPtr.Zero, null);
        ProcessStartInfo si = new ProcessStartInfo(@"c:\windows\system32\cmd.exe");
        si.Arguments = "/c " + commandLine;
        si.CreateNoWindow = false;
        si.UseShellExecute = false;
        Process proc = Process.Start(si);
        AssignProcessToJobObject(job, proc.Handle);
        return proc;
    }

    public void TerminateProc()
    {
        // terminate the Job object, which kills all processes within it
        if (job != null)
            TerminateJobObject(job, 0);
        job = IntPtr.Zero;
    }
}
Sam Protsenko
  • 14,045
  • 4
  • 59
  • 75
Riley Varga
  • 670
  • 1
  • 5
  • 15
  • The simplest way is if you started the process via teh Process Class. Then you have a perfect handle right there. – Christopher Dec 13 '19 at 23:43
  • That's what I did, so how do I close a process by it's handle rather than its ID? – Riley Varga Dec 13 '19 at 23:44
  • I do not understand. If you started it via the Process class, you got the process instance you used: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process – Christopher Dec 13 '19 at 23:45
  • Yeah, and calling "Kill" on that process won't work – Riley Varga Dec 13 '19 at 23:48
  • 1
    You need to be more specific then "does not work". What is happening or not happening? What are all those Unmanaged Window handles for, those seem extranous considering you got the Process class to wrap them all. I do not see you calling Process.Kill() or even storing the Process instance anywhere. – Christopher Dec 14 '19 at 00:23

0 Answers0