简体   繁体   English

C#杀死不存在的进程

[英]C# kill non-existent process

I wrote an TCP application and I have some problem with it. 我写了一个TCP应用程序,但遇到了一些问题。

When I run the TCP program and listen on port then the program dead, but the port is still listen. 当我运行TCP程序并在端口上侦听时,该程序已死,但该端口仍在侦听。

I want to restart it. 我想重新启动它。 It shows "System.Net.Sockets.SocektException: Only one usage of each socket is normally permitted". 它显示“ System.Net.Sockets.SocektException:通常只允许每个套接字使用一种”。

So it check the "TCPView", I found the process of the listening port is , so I tried to close it. 所以它检查了“ TCPView”,我发现监听端口的进程是,所以我试图关闭它。 Sadly fail! 可悲的是失败!

在此处输入图片说明

TCP View - non-existent TCP视图-不存在 在此处输入图片说明

Try to kill process by cmd - fail 尝试通过cmd终止进程-失败 在此处输入图片说明

So I want to know how to use c# to close the specific port. 所以我想知道如何使用c#关闭特定端口。

This sparks a memory from back in the day i was all into tcp servers and clients. 从那时起,我一直都沉浸在tcp服务器和客户端中,这激发了我的记忆。 I thought the OS took time to clean up ports from crashed or aggressively killed applications. 我以为操作系统需要花费一些时间来清理崩溃或严重终止的应用程序的端口。

If this is not the case, it might be because your application started another process, ie a child process. 如果不是这种情况,则可能是因为您的应用程序启动了另一个进程,即子进程。

Anyway, i think you should start from first principles here, if you are in control of the process you are trying to kill, its better to exit this application gracefully, and not trying to just kill it. 无论如何,我认为您应该从这里的第一个原则开始,如果您控制要杀死的进程,最好以优雅的方式退出此应用程序,而不仅仅是尝试杀死它。 Also if this application has a main window you could try calling 另外,如果此应用程序有一个主窗口,您可以尝试调用

p.CloseMainWindow();
p.WaitForExit();

Also make sure it hasn't started any child processes, as you "may" have to close them as well. 还要确保它没有启动任何子进程,因为您“可能”也必须关闭它们。

If you are in control of this application, try binding with ReuseAddress however this is just trying to make up for bad design anyway 如果您可以控制此应用程序,请尝试与ReuseAddress绑定,但是无论如何这只是试图弥补不良的设计

Allows the socket to be bound to an address that is already in use. 允许套接字绑定到已经使用的地址。

also you may want to take a look at assicoated socket options 您也可能想看看相关的插座选项

Socket.SetSocketOption Method (SocketOptionLevel, SocketOptionName, Int32) Socket.SetSocketOption方法(SocketOptionLevel,SocketOptionName,Int32)

SocketOptionName Enumeration SocketOptionName枚举

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM