1. 程式人生 > >C#在窗體程式中執行控制檯程式並管理其程序

C#在窗體程式中執行控制檯程式並管理其程序

執行環境

  • .Net Framework-4.7.1
  • visual studio 2017

一. 控制檯程式的執行

  • 使用Process類,官方文件地址

  • 使用樣例:

public void FrpStart()
{
    if (p != null)
    {
        MessageBox.Show("程序已存在");
        return;
    }
    p = new Process
    {
        // Configure the process using the StartInfo properties.
        StartInfo =
{ //呼叫的程式名稱,比如windows下的cmd,linux下的sh或者bash,即這裡要填寫控制檯程式的路徑 FileName = Utils.GetTempPath() + "/frpc.exe", //引數,MainConfig為配置檔案路徑 Arguments = "-c " + MainConfig, //控制檯程式所在的路徑 WorkingDirectory = Utils.GetTempPath
(), WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, CreateNoWindow = true, //重定向輸入輸出 RedirectStandardInput = true, RedirectStandardOutput = true } }; //監聽控制檯的輸出 p.OutputDataReceived +=
new DataReceivedEventHandler((sender, e) => { // Prepend line numbers to each line of the output. if (!string.IsNullOrEmpty(e.Data)) { append(e.Data); } }); p.Start(); p.BeginOutputReadLine(); }

注意上面新建程序的引數UseShellExecute = false,如果這裡設定為false,那麼FileName這個引數中控制檯程式的只能用絕對路徑,即WorkingDirectory引數無效。
如果不設定UseShellExecute為false,則無法重定向輸出。
如果UseShellExecute = true,則FileName可以直接使用控制檯程式的名字,前提是WorkingDirectory裡面的路徑是正確的。

二. 程序管理

接下來就是關於控制檯程序的管理了,如果僅僅按照上面編寫,程式關閉之後控制檯程式會殘留在程序中。
由於無法將控制檯程式當成執行緒執行,因此需要一個東西用來將控制檯程序與主程式關聯在一起。
這裡參考了這篇帖子

  • 繼續以上面的程式為例
public void FrpStart()
{
	//檢測是否存在殘留的執行緒,並將其關閉
    Process[] existingPrivoxy = Process.GetProcessesByName("frpc");
    foreach (Process p in existingPrivoxy)
    {
        KillProcess(p);
    }
	..........
    p.Start();
    p.BeginOutputReadLine();
    //將其加入Job
    //Job的初始化省略了,可以在建構函式初始化,使用單例模式
    Job.AddProcess(p.Handle);
}

private static void KillProcess(Process p)
{
    try
    {
        p.CloseMainWindow();
        p.WaitForExit(100);
        if (!p.HasExited)
        {
            p.Kill();
            p.WaitForExit();
        }
    }
    catch (Exception e)
    {
    }
}
  • 以上即為執行緒的啟動以及終止,最後就是Job的實現,全部都是借鑑網上的教程的,對win32的api不熟悉,這裡就不多贅述。使用該類,當主程序退出是,子程序也會退出。

public class Job : IDisposable
{
    private IntPtr handle = IntPtr.Zero;

    public Job()
    {
        handle = CreateJobObject(IntPtr.Zero, null);
        var extendedInfoPtr = IntPtr.Zero;
        var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION
        {
            LimitFlags = 0x2000
        };

        var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
        {
            BasicLimitInformation = info
        };

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

            if (!SetInformationJobObject(handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr,
                    (uint)length))
                throw new Exception(string.Format("Unable to set information.  Error: {0}",
                    Marshal.GetLastWin32Error()));
        }
        finally
        {
            if (extendedInfoPtr != IntPtr.Zero)
            {
                Marshal.FreeHGlobal(extendedInfoPtr);
                extendedInfoPtr = IntPtr.Zero;
            }
        }
    }

    public bool AddProcess(IntPtr processHandle)
    {
        var succ = AssignProcessToJobObject(handle, processHandle);

        if (!succ)
        {
            Console.WriteLine("Failed to call AssignProcessToJobObject! GetLastError=" + Marshal.GetLastWin32Error());
        }

        return succ;
    }

    public bool AddProcess(int processId)
    {
        return AddProcess(Process.GetProcessById(processId).Handle);
    }

    #region IDisposable

    private bool disposed;

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

    protected virtual void Dispose(bool disposing)
    {
        if (disposed) return;
        disposed = true;

        if (disposing)
        {
            // no managed objects to free
        }

        if (handle != IntPtr.Zero)
        {
            CloseHandle(handle);
            handle = IntPtr.Zero;
        }
    }

    ~Job()
    {
        Dispose(false);
    }

    #endregion

    #region Interop

    [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
    private static extern IntPtr CreateJobObject(IntPtr a, string lpName);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, UInt32 cbJobObjectInfoLength);

    [DllImport("kernel32.dll", SetLastError = true)]
    private static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);

    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool CloseHandle(IntPtr hObject);

    #endregion
}

#region Helper classes

[StructLayout(LayoutKind.Sequential)]
struct IO_COUNTERS
{
    public UInt64 ReadOperationCount;
    public UInt64 WriteOperationCount;
    public UInt64 OtherOperationCount;
    public UInt64 ReadTransferCount;
    public UInt64 WriteTransferCount;
    public UInt64 OtherTransferCount;
}


[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
    public Int64 PerProcessUserTimeLimit;
    public Int64 PerJobUserTimeLimit;
    public UInt32 LimitFlags;
    public UIntPtr MinimumWorkingSetSize;
    public UIntPtr MaximumWorkingSetSize;
    public UInt32 ActiveProcessLimit;
    public UIntPtr Affinity;
    public UInt32 PriorityClass;
    public UInt32 SchedulingClass;
}

[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
    public UInt32 nLength;
    public IntPtr lpSecurityDescriptor;
    public Int32 bInheritHandle;
}

[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
    public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
    public IO_COUNTERS IoInfo;
    public UIntPtr ProcessMemoryLimit;
    public UIntPtr JobMemoryLimit;
    public UIntPtr PeakProcessMemoryUsed;
    public UIntPtr PeakJobMemoryUsed;
}

public enum JobObjectInfoType
{
    AssociateCompletionPortInformation = 7,
    BasicLimitInformation = 2,
    BasicUIRestrictions = 4,
    EndOfJobTimeInformation = 6,
    ExtendedLimitInformation = 9,
    SecurityLimitInformation = 5,
    GroupInformation = 11
}

#endregion