http://www.cnblogs.com/fujinliang/archive/2012/09/13/2684165.html 原文地址

http://www.2cto.com/kf/201504/391343.html

https://msdn.microsoft.com/en-us/library/windows/desktop/ms681381(v=vs.85).aspx 错误代码

需求:很多时候我们需要后台运行几个Console来不停的计算数据,那么部署到客户服务器后,如果出现突发异常,程序挂掉了,那。。。?  
 解决方案:封装了一个对后台运行程序不停监测的功能,如果发现程序有异常,但是进程还在,这个时候就Kill掉这个进程,重启后台计算程序,这里的计算程序均为"控制台运行程序"。
异常中可以看到,Kill()进程的时候出现"拒绝访问",在网上搜了下,
解决方案大致就这几种: 在config里增加identity
<system.web>  
<identity impersonate="true" userName="Administrator" password="123456" />
</system.web> 
检测程序用"管理员身份运行"对监测的程序目录分配权限结果是这几种方式都没能解决此问题。  
 我查看了Kill()方法的注释:  
 //        // 摘要:        
//     立即停止关联的进程。     
  //        // 异常:      
  //   System.ComponentModel.Win32Exception:     
  //     未能终止关联的进程。 - 或 - 正在终止该进程。 - 或 - 关联的进程是一个 Win16 可执行文件。     
  //        //   System.NotSupportedException:       
//     您正尝试为远程计算机上运行的进程调用 System.Diagnostics.Process.Kill()。
该方法仅对在本地计算机上运行的进程可用。        //        //  
System.InvalidOperationException:       
//     该进程已经退出。 - 或 - 没有与此 System.Diagnostics.Process 对象关联的进程。       
public void Kill(); 
发现是一个Win32Exception的异常,随后我又查阅了ms的官方文档,果然有发现: 
大概意思就是说如果这个监测程序是Console,這样写是没问题的,可以正常结束掉进程。但这里因为需要在界面上展现出一些监测数据,这里我用的是WPF,也就是文档里说的图像界面程序。
 MS的原话是这样的:如果调用 Kill,则可能丢失进程编辑的数据或分配给进程的资源。
Kill
导致进程不正常终止,因而只应在必要时使用。CloseMainWindow
使进程能够有序终止并关闭所有窗口,所以对于有界面的应用程序,使用它更好。如果 CloseMainWindow 失败,则可以使用
Kill终止进程。Kill
是终止没有图形化界面的进程的唯一方法。 将Kill方法()改成了CloseMainWindow()即可正常杀掉进程。 
调用PDA中的接口调试,程序直接死了,不能结束进程,要重启wince系统。复制到PDA中程序可以正常调用扫码接口,未解之谜。。。此代码一部分用处在于此 ,尴尬。

主要代码

[MTAThread]
private static void Main()
{
try
{
IntPtr handle = CreateToolhelp32Snapshot((uint)SnapShotFlags.TH32CS_SNAPPROCESS, 0);
var pDictionary = new Dictionary<int, string>();
var strAppName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
if ((int)handle != -1)
{
var pe32 = new Processentry32 { dwSize = (uint)Marshal.SizeOf(typeof(Processentry32)) };
int bMore = Process32First(handle, ref pe32);
Processentry32 pe;
Log.WriteLog("start:" + handle.ToString());
while (bMore == 1)
{
IntPtr temp = Marshal.AllocHGlobal((int)pe32.dwSize);
Marshal.StructureToPtr(pe32, temp, true);
pe = (Processentry32)Marshal.PtrToStructure(temp, typeof(Processentry32));
Marshal.FreeHGlobal(temp);
Log.WriteLog(pe32.szExeFile + ":" + pe.th32ProcessID);
pDictionary.Add((int)pe.th32ProcessID, pe.szExeFile);
bMore = Process32Next(handle, ref pe32);
}
}
var c = pDictionary.Values.ToList().Where(x => x.StartsWith(strAppName)).ToList();
var ic = c.Count;
if (ic >= 2)
{
var p = pDictionary.Where(x => x.Value.StartsWith(strAppName));
if (MsgBoxs.ShowQMsgYes("检测到已运行该程序,是否结束上一个进程") == DialogResult.Yes)
{
foreach (KeyValuePair<int, string> keyValuePair in p)
{
try
{
if (p.LastOrDefault().Key == keyValuePair.Key) break;
Process cProcess = Process.GetProcessById(keyValuePair.Key);
cProcess.CloseMainWindow();
//cProcess.Kill();//进程异常结束会杀不死进程并且报 Win32Exception
Log.WriteLog("kill:" + keyValuePair.Value + ":" + keyValuePair.Key);
}
catch (Exception ex)
{
Log.WriteLog(ex);
throw;
}
}
}
}
var f = new FBase.MainForm();
f.DoScale();
Application.Run(f);
}
catch (Exception ex)
{
Log.WriteLog(ex);
throw;
}
} [DllImport("coredll.Dll")]
private static extern int GetLastError(); [DllImport("coredll.Dll")]
private static extern int ReleaseMutex(IntPtr hMutex); [DllImport("coredll.Dll")]
public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool InitialOwner, string MutexName); [DllImport("Toolhelp.dll")]
public static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processid); [DllImport("Coredll.dll")]
public static extern int CloseHandle(IntPtr handle); [DllImport("Toolhelp.dll")]
public static extern int Process32First(IntPtr handle, ref Processentry32 pe); [DllImport("Toolhelp.dll")]
public static extern int Process32Next(IntPtr handle, ref Processentry32 pe);

全部代码

using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using PDAClient.FBase;
using System.Diagnostics; namespace PDAClient
{
internal static class Program
{
[DllImport("coredll.Dll")]
private static extern int GetLastError(); [DllImport("coredll.Dll")]
private static extern int ReleaseMutex(IntPtr hMutex); [DllImport("coredll.Dll")]
public static extern IntPtr CreateMutex(IntPtr lpMutexAttributes, bool InitialOwner, string MutexName); [DllImport("Toolhelp.dll")]
public static extern IntPtr CreateToolhelp32Snapshot(uint flags, uint processid); [DllImport("Coredll.dll")]
public static extern int CloseHandle(IntPtr handle); [DllImport("Toolhelp.dll")]
public static extern int Process32First(IntPtr handle, ref Processentry32 pe); [DllImport("Toolhelp.dll")]
public static extern int Process32Next(IntPtr handle, ref Processentry32 pe); [StructLayout(LayoutKind.Sequential)]
public class SECURITY_ATTRIBUTES
{
public int nLength;
public int lpSecurityDescriptor;
public int bInheritHandle;
} private const int ERROR_ALREADY_EXISTS = 0183; /// <summary>
/// 应用程序的主入口点。
/// </summary>
[MTAThread]
private static void Main()
{
try
{
IntPtr handle = CreateToolhelp32Snapshot((uint)SnapShotFlags.TH32CS_SNAPPROCESS, 0);
var pDictionary = new Dictionary<int, string>();
var strAppName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
if ((int)handle != -1)
{
var pe32 = new Processentry32 { dwSize = (uint)Marshal.SizeOf(typeof(Processentry32)) };
int bMore = Process32First(handle, ref pe32);
Processentry32 pe;
Log.WriteLog("start:" + handle.ToString());
while (bMore == 1)
{
IntPtr temp = Marshal.AllocHGlobal((int)pe32.dwSize);
Marshal.StructureToPtr(pe32, temp, true);
pe = (Processentry32)Marshal.PtrToStructure(temp, typeof(Processentry32));
Marshal.FreeHGlobal(temp);
Log.WriteLog(pe32.szExeFile + ":" + pe.th32ProcessID);
pDictionary.Add((int)pe.th32ProcessID, pe.szExeFile);
bMore = Process32Next(handle, ref pe32);
}
}
var c = pDictionary.Values.ToList().Where(x => x.StartsWith(strAppName)).ToList();
var ic = c.Count;
if (ic >= 2)
{
var p = pDictionary.Where(x => x.Value.StartsWith(strAppName));
if (MsgBoxs.ShowQMsgYes("检测到已运行该程序,是否结束上一个进程") == DialogResult.Yes)
{
foreach (KeyValuePair<int, string> keyValuePair in p)
{
try
{
if (p.LastOrDefault().Key == keyValuePair.Key) break;
Process cProcess = Process.GetProcessById(keyValuePair.Key);
cProcess.CloseMainWindow();
//cProcess.Kill();//进程异常结束会杀不死进程并且报 Win32Exception
Log.WriteLog("kill:" + keyValuePair.Value + ":" + keyValuePair.Key);
}
catch (Exception ex)
{
Log.WriteLog(ex);
throw;
}
}
}
}
var f = new FBase.MainForm();
f.DoScale();
Application.Run(f);
}
catch (Exception ex)
{
Log.WriteLog(ex);
throw;
}
//if (!IsExist())
//{
// var f = new FBase.MainForm();
// f.DoScale();
// Application.Run(f);
//}
//Application.Run(new Decode_Class.Form1());
} /// <summary>
/// 判断程序是否已经运行
/// </summary>
/// <returns>
/// true: 程序已运行,则什么都不做
/// false: 程序未运行,则启动程序
/// </returns>
public static bool IsExist()
{
string strAppName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
IntPtr hMutex = CreateMutex(IntPtr.Zero, true, strAppName);
if (hMutex == IntPtr.Zero)
throw new ApplicationException("Failure creating mutex: " + Marshal.GetLastWin32Error().ToString("X")); if (Marshal.GetLastWin32Error() == ERROR_ALREADY_EXISTS)
{
ReleaseMutex(hMutex);
return true;
}
return false;
}
} [StructLayout(LayoutKind.Sequential)]
public struct Processentry32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] //注意,此处为宽字符
public string szExeFile; public uint th32MemoryBase;
public uint th32AccessKey;
} public enum SnapShotFlags : uint
{
TH32CS_SNAPHEAPLIST = 0x00000001,
TH32CS_SNAPPROCESS = 0x00000002,
TH32CS_SNAPTHREAD = 0x00000004,
TH32CS_SNAPMODULE = 0x00000008,
TH32CS_SNAPALL = (TH32CS_SNAPHEAPLIST | TH32CS_SNAPPROCESS | TH32CS_SNAPTHREAD | TH32CS_SNAPMODULE),
TH32CS_GETALLMODS = 0x80000000
}
}

wince kill 进程的更多相关文章

  1. Linux:kill 进程

    在使用Linux时,出现端口占用.进程已启动(但处于不可控状态)情况时如何处理? 发现已知端口被占用时,可以使用netstat -apn | grep yourPort 来查看占用该端口的进程的pid ...

  2. 内存不足时Android 系统如何Kill进程

    [转]内存不足时Android 系统如何Kill进程 大家其实都或多或少知道,Android系统有自已的任务管理器,当系统内存不足时,系统需要KILL一些进程(应用),以回收一部分资源,来保证系统仍可 ...

  3. rsyslog 直接kill进程,在重新启动会全部发送日志

    <pre name="code" class="html">jrhapt11:/root# ps -ef | grep rsyslog root 8 ...

  4. linux 查找并kill进程

    以php以关键字查找进程 $ ps aux | grep php root             32957   0.0  0.1  2470904   8908 s002  S+    4:53下 ...

  5. 批量kill 进程

    场景: 需要批量kill tail 进程. 解决方法: ps -ef | grep IC.IndexServer.log | grep -v grep | awk -F' ' '{print $2}' ...

  6. linux查询进程 kill进程

    查询进程 #ps aux #查看全部进程 #ps aux|grep firewall #查询与firewall相关的进程 kill进程一 kill进程pid为711进程: #pkill -9 711 ...

  7. kill 进程的一些小细节

    终止前台进程,可以用Ctrl+C组合键.但对于后台进程需要用kill命令. kill PID 还可以加信号(参数),默认情况下是编号为15的信号.term信号将终止所有不能捕捉该信号的进程. -s 可 ...

  8. Linux下查找进程,kill进程

    1. ps命令用来查找linux运行的进程,常用命令: ps aux | grep 进程名:  eg:ps aux | grep admin 查找admin的进程 或者 ps -ef | grep j ...

  9. Linux下kill进程脚本

    Linux下kill进程脚本 在Linux有时会遇到需要kill同一个程序的进程,然而这个程序有多个进程,一一列举很是繁琐,使用按名字检索,统一kill Perl脚本 使用方法 kill_all.pl ...

随机推荐

  1. Matlab Tricks(十五) —— 圆的正确画法

    使用参数方程, phi = 0:0.01:2*pi; x = cos(phi); y = sin(phi); axis equal plot(x, y) 根据参数方程,显然,圆心在 (0, 0),半径 ...

  2. 贝叶斯方法(Bayesian approach) —— 一种概率解释(probabilistic interpretation)

    1. Bayesian approach 对于多项式拟合问题,我们可通过最小二乘(least squares)的方式计算得到模型的参数,最小二乘法又可视为最大似然(maximum likelihood ...

  3. vs2008 命令窗口 命令窗口 和 反汇编窗口的使用

    visual studio 的功能相当强大,用了一年多,也只是了解了皮毛.今天学习了一下VS2008 的 即时窗口 命令窗口 和 反汇编窗口的使用.之所以会想到要使用即时窗口是因为最近开发遇到了一个问 ...

  4. WPF中,怎样将XAML代码加载为相应的对象?

    原文:WPF中,怎样将XAML代码加载为相应的对象? 在前面"在WPF中,如何得到任何Object对象的XAML代码?"一文中,我介绍了使用System.Windows.Marku ...

  5. A熟知SP.NET---WebForms UnobtrusiveValidationMode 必须“jquery”ScriptResourceMapping。

    我相信,有过ASP.NET人们学习经验RequiredFieldValidator控制(验证非空控制)一定不会陌生,禁止控制输入定义的内容的作用(该属性InitialValue的值.属性默认值为空字符 ...

  6. HTML5逐步实现

    渐变 Context对象能够通过createLinearGradient()和createRadialGradient()两个方法创建渐变对象.这两个方法的原型例如以下: Object createL ...

  7. POCO文档翻译:POCO C++库入门指南

    内容目录 介绍 Foundation库 XML库 Util库 Net库 将这些东西组合到一起 介绍 POCO C++库是一组开源C++类库的集合,它们简化及加速了用C++来开发以网络功能为核心的可移植 ...

  8. Android Studio怎样提示函数使用方法

    Eclipse有一个非常好的功能,就是当你代码调用某个android API时,鼠标移到相应的函数或者方法上,就会自己主动有一个悬 浮窗提示该函数的说明(所包括的參数含义,该方法功能).迁移到Andr ...

  9. Get and Post(Unity3D六个发展)

    猴子原创,欢迎转载. 转载请注明: 转载自Cocos2D开发网–Cocos2Dev.com,谢谢! 原文地址: http://www.cocos2dev.com/?p=565 unity3d中的www ...

  10. C# 操作XML文档 使用XmlDocument类方法

    W3C制定了XML DOM标准.很多编程语言中多提供了支持W3C XML DOM标准的API.我在之前的文章中介绍过如何使用Javascript对XML文档进行加载与查询.在本文中,我来介绍一下.Ne ...