C# 如何获取由cmd行启动(由我启动)的进程的进程ID?

C# 如何获取由cmd行启动(由我启动)的进程的进程ID?,c#,.net,process,cmd,C#,.net,Process,Cmd,因此,我使用自己的.NET进程启动命令行进程,如下所示: ProcessStartInfo startInfo=新的ProcessStartInfo() 进程执行得很好,我得到了它的输出/错误。当我想在它完成执行之前杀死它时,问题就来了。由于cmdline从技术上讲是从“PYTHON_脚本”进程本身开始的,所以我不知道该进程的进程ID是什么!因为这是我真正想杀掉的(不是命令行),我完蛋了。事实上,我已经关闭了cmd行进程,看看它是否有任何效果,但它没有 任何帮助都将不胜感激 如果不清楚的话,

因此,我使用自己的.NET进程启动命令行进程,如下所示:

ProcessStartInfo startInfo=新的ProcessStartInfo()

进程执行得很好,我得到了它的输出/错误。当我想在它完成执行之前杀死它时,问题就来了。由于cmdline从技术上讲是从“PYTHON_脚本”进程本身开始的,所以我不知道该进程的进程ID是什么!因为这是我真正想杀掉的(不是命令行),我完蛋了。事实上,我已经关闭了cmd行进程,看看它是否有任何效果,但它没有

任何帮助都将不胜感激

如果不清楚的话,问题是:“我如何杀死PYTHON_脚本(或任何其他)进程?”

编辑:对不起,我不清楚。。。我使用PYTHON_脚本作为填充。我以这种方式启动了许多不同的进程,并非所有进程都是python脚本。有些是批处理文件,有些是python脚本,有些是perl脚本,等等。我更喜欢这里的通用解决方案

编辑2:情况比问题看起来要复杂一些。例如,我正在使用SCON构建一些代码。使用“cmd/C scons”很容易。但是,启动scons过程要困难得多,因为它是一个python脚本。我传入了另一个工作目录,因此“python.exe scons.py scons”根本不起作用,“scons.bat scons”也不起作用,因为scons.bat需要查找scons.py,而scons.py不在我的工作目录中

这非常有用

                     // Get the current process.
                Process currentProcess = Process.GetCurrentProcess();


                // Get all instances of Notepad running on the local 
                // computer.
                Process [] localByName = Process.GetProcessesByName("notepad");


                // Get all instances of Notepad running on the specifiec 
                // computer. 
                // 1. Using the computer alias (do not precede with "\\").
                Process [] remoteByName = Process.GetProcessesByName("notepad", "myComputer");

                // 2. Using an IP address to specify the machineName parameter. 
                Process [] ipByName = Process.GetProcessesByName("notepad", "169.0.0.0");


                // Get all processes running on the local computer.
                Process [] localAll = Process.GetProcesses();


                // Get all processes running on the remote computer.
                Process [] remoteAll = Process.GetProcesses("myComputer");


                // Get a process on the local computer, using the process id.
                Process localById = Process.GetProcessById(1234);


                // Get a process on a remote computer, using the process id.
                Process remoteById = Process.GetProcessById(2345,"myComputer");

使用并查找“python.exe”或“pythonw.exe”进程。

通过不懈努力和google foo最终找到了答案!以下是stackoverflow答案的链接:

这是一个为我指明方向的网站:

看起来他对此做了很多研究。我当然想给他所有的荣誉。希望这个页面能帮助那些还没有找到它的人

我在为WinAPI方法找出一些D11Import的东西时遇到了一些困难,所以下面是我在其他人挂断电话时使用的代码:



        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AttachConsole(uint dwProcessId);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern bool FreeConsole();

        // Delegate type to be used as the Handler Routine for SCCH
        delegate Boolean ConsoleCtrlDelegate(CtrlTypes CtrlType);

        [DllImport("kernel32.dll")]
        static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);

        // Enumerated type for the control messages sent to the handler routine
        enum CtrlTypes : uint
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT,
            CTRL_CLOSE_EVENT,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT
        }

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GenerateConsoleCtrlEvent(CtrlTypes dwCtrlEvent, uint dwProcessGroupId);

        /// 
        /// Immediately halts all running processes under this ProcessManager's control.
        /// 
        public static void HaltAllProcesses()
        {
            for (int i = 0; i < runningProcesses.Count; i++)
            {
                Process p = runningProcesses[i];
                uint pid = (uint)p.Id;
                //This does not require the console window to be visible.
                if (AttachConsole(pid))
                {
                    //Disable Ctrl-C handling for our program
                    SetConsoleCtrlHandler(null, true);
                    GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);

                    //Must wait here. If we don't and re-enable Ctrl-C
                    //handling below too fast, we might terminate ourselves.
                    p.WaitForExit(2000);

                    FreeConsole();

                    //Re-enable Ctrl-C handling or any subsequently started
                    //programs will inherit the disabled state.
                    SetConsoleCtrlHandler(null, false);
                }

                if (!p.HasExited)
                { //for console-driven processes, this won't even do anything... (it'll kill the cmd line, but not the actual process)
                    try
                    {
                        p.Kill();
                    }
                    catch (InvalidOperationException e) 
                    {
                        controller.PrintImportantError("Process " + p.Id + " failed to exit! Error: " + e.ToString());
                    }
                }
            }
         }


[DllImport(“kernel32.dll”,SetLastError=true)]
静态外部布尔附件控制台(uint dwProcessId);
[DllImport(“kernel32.dll”,SetLastError=true,ExactSpelling=true)]
静态外部bool FreeConsole();
//要用作SCCH处理程序例程的委托类型
委托布尔控制台trlDelegate(CtrlTypes CtrlType);
[DllImport(“kernel32.dll”)]
静态外部bool SetConsoleCtrlHandler(ConsoleCtrlDelegate handler例程,bool Add);
//发送到处理程序例程的控制消息的枚举类型
枚举类型:uint
{
CTRL\u C\u事件=0,
CTRL\u BREAK\u事件,
CTRL\u CLOSE\u事件,
CTRL\u注销\u事件=5,
CTRL\u关闭\u事件
}
[DllImport(“kernel32.dll”)]
[返回:Marshallas(UnmanagedType.Bool)]
私有静态外部bool generateControlevent(CtrlTypes dwCtrlEvent,uint dwProcessGroupId);
/// 
///立即停止此ProcessManager控制下的所有正在运行的进程。
/// 
公共静态void进程()
{
for(int i=0;i

另外,如果从代码中看不出,我将存储一个同时运行的多个进程的列表,然后逐个循环以杀死它们

如果您可以运行CMD进程,并且您知道自己的进程的PID,为什么不直接使用
TASKKILL/PID 1234


我在这里没有得到的是PID的来源。

我已经看到了这一页,它对我试图完成的任务没有用处。不过谢谢。这是一个黑客。我可以让其他python进程运行,我不想把它们杀掉。另外,请参见我的编辑。我不仅仅是在运行python进程。如果你不知道进程是哪个进程,你就不能杀死它。进程名称是您仅有的信息。如果您不知道,则需要从批处理文件中找到它。Windows批处理文件并不“拥有”它们启动的Windows进程。我想要的正是Ctrl-C在命令行上所做的。cmd行是否拥有它生成的所有进程?至少不是Windows进程。如果您已经尝试杀死cmd,但失败了,那么这些进程不是它所有的。Windows不是一个非常友好的脚本环境…H


        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool AttachConsole(uint dwProcessId);

        [DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
        static extern bool FreeConsole();

        // Delegate type to be used as the Handler Routine for SCCH
        delegate Boolean ConsoleCtrlDelegate(CtrlTypes CtrlType);

        [DllImport("kernel32.dll")]
        static extern bool SetConsoleCtrlHandler(ConsoleCtrlDelegate HandlerRoutine, bool Add);

        // Enumerated type for the control messages sent to the handler routine
        enum CtrlTypes : uint
        {
            CTRL_C_EVENT = 0,
            CTRL_BREAK_EVENT,
            CTRL_CLOSE_EVENT,
            CTRL_LOGOFF_EVENT = 5,
            CTRL_SHUTDOWN_EVENT
        }

        [DllImport("kernel32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool GenerateConsoleCtrlEvent(CtrlTypes dwCtrlEvent, uint dwProcessGroupId);

        /// 
        /// Immediately halts all running processes under this ProcessManager's control.
        /// 
        public static void HaltAllProcesses()
        {
            for (int i = 0; i < runningProcesses.Count; i++)
            {
                Process p = runningProcesses[i];
                uint pid = (uint)p.Id;
                //This does not require the console window to be visible.
                if (AttachConsole(pid))
                {
                    //Disable Ctrl-C handling for our program
                    SetConsoleCtrlHandler(null, true);
                    GenerateConsoleCtrlEvent(CtrlTypes.CTRL_C_EVENT, 0);

                    //Must wait here. If we don't and re-enable Ctrl-C
                    //handling below too fast, we might terminate ourselves.
                    p.WaitForExit(2000);

                    FreeConsole();

                    //Re-enable Ctrl-C handling or any subsequently started
                    //programs will inherit the disabled state.
                    SetConsoleCtrlHandler(null, false);
                }

                if (!p.HasExited)
                { //for console-driven processes, this won't even do anything... (it'll kill the cmd line, but not the actual process)
                    try
                    {
                        p.Kill();
                    }
                    catch (InvalidOperationException e) 
                    {
                        controller.PrintImportantError("Process " + p.Id + " failed to exit! Error: " + e.ToString());
                    }
                }
            }
         }