ProjectArcade

Форк
0
156 строк · 4.5 Кб
1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Runtime.InteropServices;
6
using System.Diagnostics;
7

8
namespace EmulatorLauncher.Common
9
{
10
    public class Job : IDisposable
11
    {
12
        public static Job Current { get { if (_job == null) _job = new Job(); return _job; } }
13
        private static Job _job;
14

15

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

19
        [DllImport("kernel32.dll")]
20
        static extern bool SetInformationJobObject(IntPtr hJob, JobObjectInfoType infoType, IntPtr lpJobObjectInfo, UInt32 cbJobObjectInfoLength);
21

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

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

29
        private IntPtr handle;
30
        private bool disposed;
31

32
        public Job()
33
        {
34
            handle = CreateJobObject(IntPtr.Zero, null);
35

36
            var info = new JOBOBJECT_BASIC_LIMIT_INFORMATION
37
            {
38
                LimitFlags = 0x2000 // JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
39
            };
40

41
            var extendedInfo = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
42
            {
43
                BasicLimitInformation = info
44
            };
45

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

50
            if (!SetInformationJobObject(handle, JobObjectInfoType.ExtendedLimitInformation, extendedInfoPtr, (uint)length))
51
                throw new Exception(string.Format("Unable to set information.  Error: {0}", Marshal.GetLastWin32Error()));
52
        }
53

54
        public void Dispose()
55
        {
56
            Dispose(true);
57
            GC.SuppressFinalize(this);
58
        }
59

60
        private void Dispose(bool disposing)
61
        {
62
            if (disposed)
63
                return;
64

65
            if (disposing) { }
66

67
            Close();
68
            disposed = true;
69
        }
70

71
        public void Close()
72
        {
73
            CloseHandle(handle);
74
            handle = IntPtr.Zero;
75
        }
76

77
        public bool AddProcess(Process process)
78
        {
79
            try { return AddProcess(process.Handle); }
80
            catch { }
81

82
            return false;
83
        }
84

85
        public bool AddProcess(IntPtr processHandle)
86
        {
87
            return AssignProcessToJobObject(handle, processHandle);
88
        }
89

90
        public bool AddProcess(int processId)
91
        {
92
            return AddProcess(Process.GetProcessById(processId).Handle);
93
        }
94
    }
95

96
    #region Helper classes
97

98
    [StructLayout(LayoutKind.Sequential)]
99
    struct IO_COUNTERS
100
    {
101
        public UInt64 ReadOperationCount;
102
        public UInt64 WriteOperationCount;
103
        public UInt64 OtherOperationCount;
104
        public UInt64 ReadTransferCount;
105
        public UInt64 WriteTransferCount;
106
        public UInt64 OtherTransferCount;
107
    }
108

109

110
    [StructLayout(LayoutKind.Sequential)]
111
    struct JOBOBJECT_BASIC_LIMIT_INFORMATION
112
    {
113
        public Int64 PerProcessUserTimeLimit;
114
        public Int64 PerJobUserTimeLimit;
115
        public UInt32 LimitFlags;
116
        public UIntPtr MinimumWorkingSetSize;
117
        public UIntPtr MaximumWorkingSetSize;
118
        public UInt32 ActiveProcessLimit;
119
        public UIntPtr Affinity;
120
        public UInt32 PriorityClass;
121
        public UInt32 SchedulingClass;
122
    }
123

124
    [StructLayout(LayoutKind.Sequential)]
125
    public struct SECURITY_ATTRIBUTES
126
    {
127
        public UInt32 nLength;
128
        public IntPtr lpSecurityDescriptor;
129
        public Int32 bInheritHandle;
130
    }
131

132
    [StructLayout(LayoutKind.Sequential)]
133
    struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
134
    {
135
        public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
136
        public IO_COUNTERS IoInfo;
137
        public UIntPtr ProcessMemoryLimit;
138
        public UIntPtr JobMemoryLimit;
139
        public UIntPtr PeakProcessMemoryUsed;
140
        public UIntPtr PeakJobMemoryUsed;
141
    }
142

143
    public enum JobObjectInfoType
144
    {
145
        AssociateCompletionPortInformation = 7,
146
        BasicLimitInformation = 2,
147
        BasicUIRestrictions = 4,
148
        EndOfJobTimeInformation = 6,
149
        ExtendedLimitInformation = 9,
150
        SecurityLimitInformation = 5,
151
        GroupInformation = 11
152
    }
153

154
    #endregion
155

156
}

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.