shell中如何得到进程PID号

shell中如何得到进程PID号,第1张

用管道: 通过fgets(buf, n, ptr)buf就可以得到命令“ps -ef"一样的信息, 读帮助”man popen": char *cmd = "ps -ef"FILE *ptrif ((ptr = popen(cmd, "r")) != NULL) while (fgets(buf, n, ptr) != NULL) (void) printf("%s ",buf)UID PID...

shellexecute确实无法获取PID,采用下面两种方法可以得到正在运行的某个程序的PID:

方法一:

一、把下面代码复制到某个模块中:

Function GetPid(ExeName As String) As Long

On Error Resume Next

Dim objWMIService, colProcessList, objProcess

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

Set colProcessList = objWMIService.ExecQuery _

("Select * from Win32_Process Where Name='" &ExeName &"'")

For Each objProcess In colProcessList

GetPid = objProcess.Handle

Exit For

Next

Set objProcess = Nothing

Set colProcessList = Nothing

Set objWMIService = Nothing

End Function

二、调用举例:

dim PID as long

ShellExecute 0&, "open", "calc.exe", 0, 0, 1

PID=GetPid("calc.exe")

MsgBox PID

方法二(推荐):

一、把下面代码复制到某个模块中:

'声明

Private Declare Function FindExecutable Lib _

"shell32.dll" Alias "FindExecutableA" _

(ByVal lpFile As String, ByVal lpDirectory _

As String, ByVal lpResult As String) As Long

'自定义函数

Public Function SpeShellExecute(FileName As String) As Long

Dim Ret As Integer

Dim Bfr As String

Dim ExPath As String

Dim Ext As String

If Dir(FileName) = "" Or FileName = "" Then

Exit Function

End If

Bfr = String(300, 32)

Ext = Right$(FileName, 3)

If Ext = "exe" Or Ext = "com" Or Ext = "bat" Then

SpeShellExecute = Shell(FileName, vbNormalFocus)

Else

Ret = FindExecutable(FileName, vbNullString, Bfr)

If Ret >32 Then

ExPath = Left$(Bfr, InStr(Bfr, Chr$(0)) - 1)

SpeShellExecute = Shell(ExPath &" " &FileName, vbNormalFocus)

Else

MsgBox "No association for file type:" &UCase(Ext)

End If

End If

End Function

二、调用举例:

dim PID as long

PID=SpeShellExecute("c:\1.jpg") '用SpeShellExecute代替ShellExecute!

MsgBox PID

如果是要监听的服务端口,我觉得用 l 参数比较好。

然后如下三种方式请参考。

netstat -nlp | grep -w 端口号 | sed -r 's#.* (.*)/.*#\1#'

netstat -nlp | sed -nr '/端口号/s#.* (.*)/.*#\1#p'

netstat -nlp | awk -F'[ /]*' '/端口号/{print $(NF-2)}'


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/yw/11998618.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-20
下一篇2023-05-20

发表评论

登录后才能评论

评论列表(0条)

    保存