1

そこで、独自の .NET プロセスを使用して、次のようにコマンド ライン プロセスを開始します。 ProcessStartInfo startInfo = new ProcessStartInfo();

        Process p = new Process();
        startInfo.CreateNoWindow = true;
        startInfo.RedirectStandardOutput = redirectOutput;
        startInfo.RedirectStandardError = redirectError;
        //startInfo.WindowStyle = ProcessWindowStyle.Hidden; //is this necessary for cmd line commands?
        startInfo.RedirectStandardInput = false;
        startInfo.UseShellExecute = false;
        String arguments = "/C PYTHON_SCRIPT";
        startInfo.Arguments = arguments;
        String pathToProcess = "cmd.exe";
        startInfo.FileName = pathToProcess;
        startInfo.WorkingDirectory = workingDirectory;
        p.StartInfo = startInfo;
        p.Start();

プロセスは問題なく実行され、その出力/エラーが表示されます。問題は、実行が完了する前に強制終了したい場合です。コマンドラインは技術的に「PYTHON_SCRIPT」プロセス自体から開始されたため、そのプロセスのプロセスIDが何であるかわかりません! それは私が本当に殺したいものなので(コマンドラインではありません)、私はめちゃくちゃです。実際、コマンドラインプロセスを強制終了して、効果があるかどうかを確認しましたが、効果はありません。

どんな助けでも大歓迎です。

明確でない場合は、「PYTHON_SCRIPT (またはその他の) プロセスを強制終了するにはどうすればよいですか?」という質問があります。

編集:申し訳ありませんが、明確ではありませんでした...私は PYTHON_SCRIPT をフィラーとして使用しています。私はこの方法でさまざまなプロセスを開始していますが、そのすべてが python スクリプトであるとは限りません。一部はバッチ ファイル、一部は python スクリプト、一部は perl スクリプトなどです。

編集 2: 状況は、質問から見えるよりも少し複雑です。たとえば、scons を使用してコードを作成しています。「cmd /C scons」を使用するのは簡単です。ただし、scons プロセスの開始は、Python スクリプトであるため、はるかに困難です。別の作業ディレクトリを渡すので、「python.exe scons.py scons」はまったく機能せず、「scons.bat scons」も機能しません。scons.bat は scons.py を見つける必要があり、scons.py は見つからないからです。私の作業ディレクトリにはありません。

4

4 に答える 4

2

最後に、多くの忍耐力とGoogle fooで答えを見つけました! これがstackoverflowの回答へのリンクです:

https://stackoverflow.com/a/15281070/476298

そして、ここに私をその方向に向けたウェブサイトがあります:

http://stanislavs.org/stopping-command-line-applications-programatically-with-ctrl-c-events-from-net/

彼はこれについてたくさんの研究をしたようです。間違いなく彼にすべての信用を与えたい. このページが、まだ見つけていない他の人に役立つことを願っています!

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());
                    }
                }
            }
         }

PSコードから明らかでない場合は、同時に実行されている複数のプロセスのリストを保存し、それらを1つずつループしてすべてを強制終了しています。

于 2013-09-11T17:45:02.240 に答える
1

CMD プロセスを実行でき、プロセスの PID を知っている場合は、単純に を使用してみませんTASKKILL /PID 1234か?

ここで得られなかったのは、PID の取得元です。

于 2015-11-26T23:18:00.603 に答える
0

このリンクは非常に便利です

                     // 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");
于 2013-09-06T23:05:04.407 に答える