Solved

Passing data between two processes using StandardOutput/StandardInput

Posted on 2008-10-13
16
735 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
  • 8
  • 5
  • 3
16 Comments
 
LVL 5

Accepted Solution

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

Author Comment

by:AWestEng
Comment Utility
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
Comment Utility
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
 
LVL 1

Author Comment

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

Author Comment

by:AWestEng
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 21

Assisted Solution

by:mastoo
mastoo earned 50 total points
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
thx anyway
0
 
LVL 1

Author Comment

by:AWestEng
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

Suggested Solutions

In my previous article (http://www.experts-exchange.com/Programming/Languages/.NET/.NET_Framework_3.x/A_4362-Serialization-in-NET-1.html) we saw the basics of serialization and how types/objects can be serialized to Binary format. In this blog we wi…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video demonstrates how to create an example email signature rule for a department in a company using CodeTwo Exchange Rules. The signature will be inserted beneath users' latest emails in conversations and will be displayed in users' Sent Items…

771 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now