Process question

N

Nikolay Petrov

I have a class which starts a process and redirects it's output and input.
My class have a method which starts the process and another which stops it.
How can I check if the process have been already started, so I don't try to
start it again, and how to check if the process is not running so i don't
try to stop again?

code:
Public Class ProcEx
Private p As Process
Public Sub StartProcess()
p = New Process
With p.StartInfo
.FileName = "cmd"
.Arguments = ""
.CreateNoWindow = True
.ErrorDialog = False
.RedirectStandardError = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.UseShellExecute = False
.WindowStyle = ProcessWindowStyle.Hidden
.WorkingDirectory = Application.StartupPath
End With
p.Start()
End Sub
Public Sub StopProcess()
Dim RetVal As String
If Not p.HasExited Then
p.Kill()
End If
p.Close()
'p.Dispose()
End Sub
End Class
 
A

Adam Goossens

Hi Nikolay,

Try Process.GetProcessesByName(). It will return to you a Process array
of all processes with the name you provide.

If the array is not empty, then you know the process has already been
started and you can take a reference to the old process rather than
create a new one.

---
Dim aProcesses() as Process
aProcesses = Process.GetProcessesByName("yourexecutable")

If aProcesses.Length > 0 Then
' process has been started before:
p = aProcesses(0)
Else
p = New Process
' initialize it here.
End If
 
N

Nikolay Petrov

thanks
I have a question
I am using my app to run instance of cmd.exe
what if there is another cmd.exe started outside of my process?
 
A

Adam Goossens

Hi,

AFAIK that shouldn't make a difference. All processes with the matching
name should get returned by Process.GetProcessesByName.

Regards,
-Adam.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top