Passing data between two processes using StandardOutput/StandardInput

Hi!

I have 2 applications: App1 and App2
1: In App1 I send a command to App2
2: In App1 I like to know if this command was executed as it should, so I need some data back from App2 to App1

I do this In App1 and app2

---------------------------------------------------------------------------------------------------------------------------
This is pseudocode so don't focus on all the code in the methods ,just the bit how to send back some data from app2 to app1.
---------------------------------------------------------------------------------------------------------------------------
'///// THIS CODE IS IN APP1
    Private Sub App1_StartApp2()
        Dim myprocess As New Process
        Dim processData As String
 
        '// Set process parameters for a controlled shutdown
        With myprocess.StartInfo
            .FileName = applicationPath & server & ".exe"
            .Arguments() = "/input=True,True"
            .CreateNoWindow = False
            .ErrorDialog = False
            .UseShellExecute = False
            .RedirectStandardOutput = True
            .RedirectStandardError = True
            .RedirectStandardInput = True
            .WindowStyle = ProcessWindowStyle.Normal
        End With
 
        myprocess.Start()
        myprocess.WaitForInputIdle(1000)
 
        Dim standardOutput As IO.StreamReader = myprocess.StandardOutput
 
        ' Wait for Exited event, but not more than 10 seconds.
        Const SLEEP_AMOUNT As Integer = 100
        Do While Not m_shutDownProcessExited
            m_shutDownElapsedTime += SLEEP_AMOUNT
            '// Get process output
            processData = standardOutput.ReadToEnd
            If m_shutDownElapsedTime > 10000 Then
                myprocess.Kill()
                Exit Do
            End If
            Thread.Sleep(SLEEP_AMOUNT)
        Loop
 
        If processData = "True" Then
            '.... DO some stuff
        Else
            ' Do some other stuff
        End If
    End Sub
 
'///// THIS CODE IS IN APP2
    ''
    'In App2 (This works so just focus on the sending back data)
    ''
    Private Sub MyApplication_StartupNextInstance(ByVal sender As Object, ByVal e As Microsoft.VisualBasic.ApplicationServices.StartupNextInstanceEventArgs) Handles Me.StartupNextInstance
        Dim inputArgument As String = "/input="
        Dim args As String()
        Dim serverStopped As Boolean = False
 
        Dim inputData As String = String.Empty
 
        If e.CommandLine.Count > 0 Then
            inputData = e.CommandLine(0)
        End If
 
        If inputData.ToLower.StartsWith(inputArgument) Then
            Dim inputName As String = inputData.Remove(0, inputArgument.Length)
 
            args = inputName.Split(CChar(","))
        End If
 
        Dim value As Boolean = CBool(args(0))
 
        If value Then
            '// Execute method
            serverStopped = server.Stop()
 
            '// Create Process Start information 
            Dim processStartInfo As New ProcessStartInfo()
 
            With processStartInfo
                .FileName = server.FullPath
                .Arguments = serverStopped.ToString
                .WindowStyle = ProcessWindowStyle.Hidden
                .CreateNoWindow = True
                .ErrorDialog = False
                .UseShellExecute = False
                .RedirectStandardError = True
                .RedirectStandardOutput = True
                .RedirectStandardInput = True
            End With
 
            '// Execute the process 
            Dim process As New Process()
            process.StartInfo = processStartInfo
            Dim processStarted As Boolean = process.Start()
 
            '// SEND BACK THE DATA ????????????? NEED HELP HERE
 
            process.WaitForExit(1000)
 
            '// HasExited is true if the application closed before the time-out.
            If process.HasExited = False Then
                'Process is still running.
                'Test to see if process is hung up.
                If process.Responding = False Then
                    'Process was not responding; force the process to close.
                    process.Kill()
                End If
            End If
 
        End If
    End Sub

Open in new window

LVL 1
AWestEngAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
Ignacio Soler GarciaConnect With a Mentor Solution Architech & Technical LeadCommented:
It wouldn't be easier to open a socket and communicate thru a single Network stream?
0
 
AWestEngAuthor Commented:
hmm don't know,
I really want fix the concept I already have, but If you can show me how to solve it I'm listening
0
 
Ignacio Soler GarciaSolution Architech & Technical LeadCommented:
It pretty simple. One process opens a socket and the other one connects to it. Then both processes can talk to each other.

I'm sorry but I have not code here to show you that.
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
AWestEngAuthor Commented:
And I use the "internal2 Framework, I can't use Sub Main Method
 
 
0
 
AWestEngAuthor Commented:
ok. why I like to use the the process stuff and no network is because this must work even if the network card is broken. don't know it the socket method  uses the newtwork card?
0
 
mastooCommented:
I'm not quite following what you are doing but I believe the concept is sound.  App1 starts App2 with App2 i/o redirected.  App1 waits on App2 to complete.  App2 just needs to write to stdout and App1 will receive that output.  Is there more?
0
 
Ignacio Soler GarciaSolution Architech & Technical LeadCommented:
The sockets way will work always as you always have the Loopback connection (127.0.0.1).

Just look for classes Net.TcpListener and Net.TcpClient for example.
0
 
AWestEngAuthor Commented:
mastoo: you are correct
1> App1 start App2. ----------------------------This works!!!
2> App1 sends execute methods M1------This works!!!
3> App1 waits in do while loop until App2 says, M1 return this result------Need help
 
you can see the do while loop in the code I have posted. Now I need some help to send the data back from App to App1
0
 
mastooConnect With a Mentor Commented:
The VS help for RedirectStandardOutput has some good examples for this.  The easiest would be have App1 wait for App2 to exit and then read the output, assuming App2 doesn't have much to say (this is the race condition mentioned in the help).  You can prototype it with that, and then if you desire change over to asynchronous reads of stdout to eliminate the possible race condition (somewhat more complicated).  I've written things that have run fine for years now just using the simple case since my App2 is only outputing trivial things.
0
 
AWestEngAuthor Commented:
do you have an example how to solve it, I have checked a few examples but I can't get it to work :(
0
 
mastooCommented:
This snippet should work if your app2 just writes a line to stdout and quits.  How about try that first and you can build from there.  The limitation on this simplistic example is that App2 writing too much (overflowing the buffer) or not writing anything (a logic bug) causes your app1 to hang but you can eliminate those during debugging.
'///// THIS CODE IS IN APP1
    Private Sub App1_StartApp2()
        Dim myprocess As New Process
        Dim processData As String
 
        '// Set process parameters for a controlled shutdown
        With myprocess.StartInfo
            .FileName = applicationPath & server & ".exe"
            .Arguments() = "/input=True,True"
            .CreateNoWindow = False
            .ErrorDialog = False
            .UseShellExecute = False
            .RedirectStandardOutput = True
            .RedirectStandardError = True
            .RedirectStandardInput = True
            .WindowStyle = ProcessWindowStyle.Normal
        End With
        myprocess.Start()
        myProcess.WaitForExit() 
        processData = standardOutput.ReadToEnd
        If processData = "True" Then
            '.... DO some stuff
        Else
            ' Do some other stuff
        End If
    End Sub

Open in new window

0
 
AWestEngAuthor Commented:
thx anyway
0
 
AWestEngAuthor Commented:
This is what I have now.
 
But hen App2 says
StandardIn has not been redirected

In App1
--------------------------------------------------
        Dim myprocess As New Process
        Dim processData As String
 
        With myprocess.StartInfo
            .FileName = applicationPath & server & ".exe"
            .Arguments() = "/input=True,True"
            .CreateNoWindow = False
            .ErrorDialog = False
            .UseShellExecute = False
            .RedirectStandardOutput = True
            .RedirectStandardError = True
            .RedirectStandardInput = True
            .WindowStyle = ProcessWindowStyle.Normal
        End With
 
        myprocess.Start()
 
        Dim standardOutput As IO.StreamReader = myProcess.StandardOutput
 
        '// Wait for Exited event, but not more than 10 seconds.
        Const SLEEP_AMOUNT As Integer = 100
        Do While Not m_shutDownProcessExited
            m_shutDownElapsedTime += SLEEP_AMOUNT
            '// Read the standard output of the spawned process.
            processData = standardOutput.ReadToEnd
            If Not String.IsNullOrEmpty(processData) Then
                Exit Do
            End If
            '// Timout?
            If m_shutDownElapsedTime > 10000 Then
                myProcess.Kill()
                Exit Do
            End If
            Thread.Sleep(SLEEP_AMOUNT)
        Loop
 
        If processData = "True" Then
            'Do some stuff
        Else
            ' Do some other stuff
        End If
 
In App2
--------------------------------------------------
        Dim runningProcesses As Process()
        Dim runningProcess As Process = Nothing
 
        runningProcesses = Process.GetProcessesByName(server.FullPath)
 
        If runningProcesses.Length > 0 Then
            For Each p As Process In runningProcesses
                If p.ProcessName = server.Name Then
                    runningProcess = p
                    Exit For
                End If
            Next
        End If
 
        If runningProcess IsNot Nothing Then
            runningProcess.StandardInput.Write("True")
        End If

Open in new window

0
 
mastooCommented:
Your app2 should just write to stdout and app1 will receive it via the redirection:

In App2
--------------------------------------------------
        System.Console.WriteLine("True")
0
 
AWestEngAuthor Commented:
so the code in app1 is ok?
I changes the code in App2 to
System.Console.WriteLine("True")
 
But it didn't work
0
 
mastooCommented:
You changed app1 code to look like my earlier post?  You can run app2 from a command prompt also just to make sure it prints "True" and stops.  Then step through app1 in the debugger.  What's it do?
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.