Process: StandardOutput - vb.net

I try to communicate between 2 processes, one written in Vb.net and the other written in Tcl. My goal is to start the program in tcl through System.Diagnostics.Process() and communicate with the standard output of Tcl.
Dim form As New System.Diagnostics.Process()
form.StartInfo.RedirectStandardOutput = True
form.StartInfo.RedirectStandardError = False
form.StartInfo.UseShellExecute = False
form.StartInfo.CreateNoWindow = True
form.StartInfo.Arguments = myargs
form.StartInfo.FileName = "wish.exe"
form.Start()
Dim output As String = Nothing
While Not form.StandardOutput.EndOfStream
output = form.StandardOutput.ReadLine()
If output.Contains("IMAGE=") Then
' Do stuff...
End If
End While
form.Close()
It works, but I would like to send an info to my Vb.net program to tell it to stop like this :
If output.Contains("EXIT") Then
Exit While
End If
And finally let my Tcl program redirect its standard output to my wish.exe console like this :
# communication with vb.net program
foreach prt $fileimage {
puts "IMAGE=$prt"
}
# exit vb.net program
puts "EXIT"
# puts others 'info' in my wish.exe console
puts "info..." ; # problem here > 'info...' is not visible in my console
The problem I have is that when I exit my program, the standard output of Tcl is no longer redirected to my console...
My question : What is the best way to get out of my program without losing the standard Tcl output?

Related

run external program and exit from calling program

n the closing procedure of a program (just before running Application.exit) I need to run an external program to pass a parameter and exit the calling program.
The program called (FilmDB_Update.exe) has the task of overwriting the main program or a dll library.
I tried to use the "process.start" technique, but apparently, the calling program remains in use and does not allow me to overwrite it.
This is the code that I write:
Private Sub AggiornaPgm()
Dim ws_file As String = "FilmDB_Update.exe"
Dim ws_proc_param As String = """" + ws_working_path + """ " + ws_temp_path
Dim ws_fullPath As String = Path.Combine(ws_temp_path, ws_file)
If File.Exists(ws_fullPath) Then
File.Copy(ws_fullPath, ws_file, True)
End If
Dim proc As New System.Diagnostics.Process()
proc = Process.Start(ws_file, ws_proc_param)
End Sub
I wanted to try using the shell command, but I can not pass the parameters to the called program.
Does any of you have any other ideas about it?
Thank you
Marcello
As Ahmed suggested, I added the test for the calling process to the program called.
p = Process.GetProcessesByName(ws_calling_pgm)
While p.Count > 0
Threading.Thread.Sleep(3000)
p = Process.GetProcessesByName(ws_calling_pgm)
End While
p = Nothing
When I exit the While loop, the calling process is terminated. I do not understand why, despite the process no longer exists, the main program is still in use.

Writing to Command Line Not Working

An application I need to use (USB capture utility) has a .cmd version that I can call from my Visual Basic code. I am able to launch the application and put it in "command line mode" like this:
Public Class MyClass
Dim StreamWriteUtility As System.IO.StreamWriter
Dim StreamReadUtility As System.IO.StringReader
Dim ProcessInfo As ProcessStartInfo
Dim Process As Process
Public Sub StartUSBCapture(ByVal DataStorageLocation As String)
Dim ProcessInfo As ProcessStartInfo
Dim Process As New Process
ProcessInfo = New ProcessStartInfo("C:\FW_Qualification_Suite\data-center-windows\data-center\bin\datacenter.cmd", "-c ")
ProcessInfo.CreateNoWindow = True
ProcessInfo.UseShellExecute = False 'Must be changed if redirect set to True
ProcessInfo.RedirectStandardInput = True
Process = Process.Start(ProcessInfo)
SWUtility = Process.StandardInput
While True
SWUtility.WriteLine("run") 'Looping for test to ensure this isn't a timing issue
End While
End Sub
End Class
This launches the application and opens a separate command line window that should accept further commands (i.e., capture, run, stop, etc). However, I am having trouble getting those subsequent commands to show up in the command line window. I've tried redirecting the standard input of the process, but still nothing shows up in the console window.
Can anyone tell how I'm supposed to actually get these commands from my Visual Basic program into this application?

Get output of external console app to RichTextBox

I used the VB.Net Shell() command to start a console app that I haven't created. I want to get the lines from that console to a RichTextBox in my form. It should be possible because I have seen many apps that do this. Please provide some information or any program that might help me. I tried to see if the external app creates log files, but it does not.
Here's how I started. What should I add, and where, to return the output?
Try
writer.WriteLine(RichTextBox1.Text)
writer.Close()
Shell(CurDir() & "\yelloeye.exe .\new.demo")
Catch ex As Exception
MsgBox(ex.Message)
End Try
Here's an example using the RedirectStandardOutput property as mentioned by #Plutonix which will ping SO and display the results in a RichTextBox. Just replace the .exe name and arguments (if any) to suit your needs.
Private Sub ShellToRTB()
Dim p As New Process()
p.StartInfo.FileName = "ping.exe"
p.StartInfo.Arguments = "www.stackoverflow.com"
p.StartInfo.UseShellExecute = False
p.StartInfo.RedirectStandardOutput = True
p.Start()
RichTextBox1.Text = p.StandardOutput.ReadToEnd()
p.WaitForExit()
End Sub
Result:

Respond to commandline program question in VB.net

I'm using VB.net to have a GUI on top of a commandline program.
Dim sqliProcess As New Process()
sqliProcess.StartInfo.UseShellExecute = False
sqliProcess.StartInfo.RedirectStandardOutput = True
sqliProcess.StartInfo.RedirectStandardError = True
sqliProcess.StartInfo.FileName = "C:\shell_program.exe"
sqliProcess.StartInfo.CreateNoWindow = True
sqliProcess.Start()
Do While Not bw.CancellationPending
Try
If Not sqliProcess.StandardOutput.EndOfStream Then
Debug.Print(sqliProcess.StandardOutput.ReadLine)
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error reading output")
End Try
Threading.Thread.Sleep(1)
Loop
Which works and prints out all output from the commandline program. However at some point the commandline program ask for user interaction, eg:
Type a number (1/2/3/4):
But the commandline program stops after this. I suspect this is because it doesn't receive a valid option.
Is there a way to capture when the commandline program wants user interaction and hold the reading of the stream to be able to enable the user to input something?
It's not that hard if you use the events. (Don't forget EnableRaisingEvents). Look here at outputdatareceived..

Pick up strings from cmd command? Process.StartInfo

so I've tried Process and starting a cmd.exe and send commands directly to that window. And then picking up the values written to the cmd.exe window.
The code looks like this:
Dim arrServers As ArrayList
Dim s(ListBoxServers.Items.Count) As String
ListBoxServers.Items.CopyTo(s, 0)
arrServers = New ArrayList(s)
Using P As New Process
P.StartInfo.FileName = "cmd.exe"
P.StartInfo.UseShellExecute = False
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardInput = True
P.Start()
For Each i In arrServers
P.StandardInput.WriteLine("query user " & txtBoxUsername.Text & " /server:" & i)
Next
P.StandardInput.WriteLine("exit")
Output = P.StandardOutput.ReadToEnd()
Trace.WriteLine(Output)
MsgBox(Output)
P.WaitForExit()
End Using
But is looks like it doesn't "press enter" or something. Meaning, I don't get any results from the command. I don't even get a "'command' is not recognized as an internal or external command, operable program or batch file." like you normally get if it doesn't understand the syntax.
Look into the Process class in the System.Diagnostics namespace for running your batch file.
Imagine the following really simple batch file called "hello.bat"
#ECHO OFF
echo Hello
You can call it and see "Hello" by using:
'Will hold the results of the batch
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run
P.StartInfo.FileName = "c:\scripts\hello.bat"
'My script doesn't take argument but this is where you would pass them
P.StartInfo.Arguments = ""
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to see the output
P.StartInfo.RedirectStandardOutput = True
'Start your batch
P.Start()
'Read the entire contents of the outout
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine("Batch produced : " & Output)
Edit
Here's a version that doesn't run a batch but instead runs a couple of standard commands. We start by firing up a command shell to pass things to. One thing that sucks is that its hard to run a command, read the output and then run another command. The code below runs two commands back-to-back and dumps the entire result into a string. If you have a need for running a command, processing, running another command, I think you'll have to wire up something to StandardError and look at return codes. Before you do that, make sure you read up on problem with blocking and how other places solve it by wiring threads up such as here. Probably the easier way is to wrap this into a sub and call the sub once for each command.
'Will hold all of the text
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run the standard command shell
P.StartInfo.FileName = "cmd.exe"
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to read/write to it
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardInput = True
'Start your batch
P.Start()
'Send your various commands
P.StandardInput.WriteLine("dir c:\")
P.StandardInput.WriteLine("ipconfig /all")
'Very important, send the "exit" command otherwise STDOUT will never close the stream
P.StandardInput.WriteLine("exit")
'Read the entire stream
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine(Output)
Edit 2
I'm having problems with the "query user" command in general, I can't get it to return anything for usernames with spaces in them even if I enclose the name in quotes. But here's a version that uses "quser" instead which does the exact same thing as far as I know.
'Will hold all of the text
Dim Output As String
'Create a new process object
Using P As New Process()
'Set the script to run the standard command shell
P.StartInfo.FileName = "cmd.exe"
'Required to redirect output, don't both worrying what it means
P.StartInfo.UseShellExecute = False
'Tell the system that you want to read/write to it
P.StartInfo.RedirectStandardOutput = True
P.StartInfo.RedirectStandardInput = True
'Start your batch
P.Start()
'Send your various commands
'Array of servers
Dim arrServers() As String = New String() {"SERVER1", "SERVER2"}
'Loop through array, wrap names with quotes in case they have spaces
For Each S In arrServers
P.StandardInput.WriteLine(String.Format("quser ""{0}"" /SERVER:{1}", Me.txtBoxUsername.Text, S))
Next
'Very important, send the "exit" command otherwise STDOUT will never close the stream
P.StandardInput.WriteLine("exit")
'Read the entire stream
Output = P.StandardOutput.ReadToEnd()
'Wait until the batch is done running
P.WaitForExit()
End Using
'Do something with the output
Trace.WriteLine(Output)
Use a library/class like NDesk's Options for flexible argument handling. If you don't want to use a external component, you'll have to loop over the arguments and process them manually:
For Each arg As String In Environment.GetCommandLineArgs()
Select Case arg
Case "/blah"
' process /blah '
Case "/foo"
' process foo '
Case Else
MsgBox "Unknown argument " + arg " found, aborting.", vbCritical
Environment.Exit(1)
End Select
Next
[I normally don't do VB, so this is just an untested sketch]