Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class PipeServer
- {
- static
- int
- Main(string[] args)
- {
- if(args.Length < 2
- ||(System.String.Compare(args[0], "in") != 0
- && System.String.Compare(args[0], "out") != 0)) {
- System.Console.WriteLine("Usage: PipeServer <in | out> <process> <args>");
- return 1;
- }
- ///////////////////////////////////
- // // // Process arguments // // //
- ///////////////////////////////////
- // Convert pipe direction
- System.IO.Pipes.PipeDirection pipe_dir = 0;
- if(System.String.Compare(args[0], "in") == 0) {
- pipe_dir = System.IO.Pipes.PipeDirection.In;
- }
- if(System.String.Compare(args[0], "out") == 0) {
- pipe_dir = System.IO.Pipes.PipeDirection.Out;
- }
- // Find process name to start
- string proc_name = args[1];
- // Build commandline argument string
- string proc_args = "";
- for(System.UInt16 i = 2; i < args.Length; i++) {
- if(args[i].IndexOf(" ") > -1) {
- proc_args += "\"" + args[i].Replace("\"", "\\\"") + "\" ";
- } else {
- proc_args += args[i] + " ";
- }
- }
- // Create server
- string pipe_name = "";
- System.IO.Pipes.NamedPipeServerStream pipe_stream = null;
- for(System.UInt16 i = 1; i < 65535; i++) {
- // Generate new pipe name
- pipe_name = "pipeserver_" + System.Convert.ToString(i);
- try {
- // Start server
- pipe_stream = new System.IO.Pipes.NamedPipeServerStream(pipe_name, pipe_dir, 1);
- break;
- } catch(System.IO.IOException _) {
- continue;
- }
- }
- if(pipe_stream == null) {
- System.Console.WriteLine("Could not create pipe");
- return 1;
- }
- // Make sure the process knows about the pipe name
- proc_args = proc_args.Replace("{pipe}", "\\\\.\\pipe\\" + pipe_name);
- // Run process
- System.Diagnostics.Process proc = new System.Diagnostics.Process();
- proc.StartInfo.FileName = proc_name;
- proc.StartInfo.Arguments = proc_args;
- proc.Start();
- // Connect pipes and wait until EOF
- pipe_stream.WaitForConnection();
- try {
- if(pipe_dir == System.IO.Pipes.PipeDirection.In) {
- pipe_stream.CopyTo(System.Console.OpenStandardOutput());
- }
- if(pipe_dir == System.IO.Pipes.PipeDirection.Out) {
- System.Console.OpenStandardInput().CopyTo(pipe_stream);
- }
- } catch (System.IO.IOException e) {
- System.Console.WriteLine("error: {0}", e.Message);
- return 1;
- }
- // Wait for process termination
- while(!proc.HasExited) {
- proc.WaitForExit();
- }
- // Return correct exit code
- return proc.ExitCode;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement