Solved

Passing data between two processes using StandardOutput/StandardInput

Posted on 2008-10-13
16
757 Views
Last Modified: 2013-11-07
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

0
Comment
Question by:AWestEng
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 5
  • 3
16 Comments
 
LVL 5

Accepted Solution

by:
Ignacio Soler Garcia earned 450 total points
ID: 22701915
It wouldn't be easier to open a socket and communicate thru a single Network stream?
0
 
LVL 1

Author Comment

by:AWestEng
ID: 22702424
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
 
LVL 5

Expert Comment

by:Ignacio Soler Garcia
ID: 22702457
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
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:AWestEng
ID: 22702460
And I use the "internal2 Framework, I can't use Sub Main Method
 
 
0
 
LVL 1

Author Comment

by:AWestEng
ID: 22702487
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
 
LVL 21

Expert Comment

by:mastoo
ID: 22702629
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
 
LVL 5

Expert Comment

by:Ignacio Soler Garcia
ID: 22702643
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22702712
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
 
LVL 21

Assisted Solution

by:mastoo
mastoo earned 50 total points
ID: 22703944
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22703998
do you have an example how to solve it, I have checked a few examples but I can't get it to work :(
0
 
LVL 21

Expert Comment

by:mastoo
ID: 22705153
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
 
LVL 1

Author Comment

by:AWestEng
ID: 22706063
thx anyway
0
 
LVL 1

Author Comment

by:AWestEng
ID: 22710426
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
 
LVL 21

Expert Comment

by:mastoo
ID: 22711346
Your app2 should just write to stdout and app1 will receive it via the redirection:

In App2
--------------------------------------------------
        System.Console.WriteLine("True")
0
 
LVL 1

Author Comment

by:AWestEng
ID: 22712979
so the code in app1 is ok?
I changes the code in App2 to
System.Console.WriteLine("True")
 
But it didn't work
0
 
LVL 21

Expert Comment

by:mastoo
ID: 22714659
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

Featured Post

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.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question