Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.IO;
- using System.Runtime.InteropServices;
- using System.Text;
- class Program
- {
- const uint PIPE_ACCESS_OUTBOUND = 0x00000002;
- const uint PIPE_TYPE_BYTE = 0x00000000;
- const uint PIPE_READMODE_BYTE = 0x00000000;
- const uint PIPE_WAIT = 0x00000000;
- const uint PIPE_UNLIMITED_INSTANCES = 255;
- const uint FILE_FLAG_OVERLAPPED = 0x40000000;
- [StructLayout(LayoutKind.Sequential)]
- public struct SECURITY_ATTRIBUTES
- {
- public int nLength;
- public IntPtr lpSecurityDescriptor;
- public int bInheritHandle;
- }
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern IntPtr CreateNamedPipe(
- string lpName,
- uint dwOpenMode,
- uint dwPipeMode,
- uint nMaxInstances,
- uint nOutBufferSize,
- uint nInBufferSize,
- uint nDefaultTimeOut,
- IntPtr lpSecurityAttributes);
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern int ConnectNamedPipe(
- IntPtr hNamedPipe,
- IntPtr lpOverlapped);
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern int WriteFile(
- IntPtr hFile,
- byte[] lpBuffer,
- uint nNumberOfBytesToWrite,
- out uint lpNumberOfBytesWritten,
- IntPtr lpOverlapped);
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern int CloseHandle(IntPtr hObject);
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern IntPtr GetStdHandle(int nStdHandle);
- static void Main()
- {
- string pipeName = @"\\.\pipe\MyNamedPipe";
- IntPtr hPipe;
- // Create the named pipe
- hPipe = CreateNamedPipe(pipeName, PIPE_ACCESS_OUTBOUND, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
- PIPE_UNLIMITED_INSTANCES, 0, 0, 0, IntPtr.Zero);
- if (hPipe == IntPtr.Zero || hPipe.ToInt32() == -1)
- {
- Console.WriteLine("Error creating named pipe: " + Marshal.GetLastWin32Error());
- return;
- }
- // Wait for a client to connect
- Console.WriteLine("Waiting for client to connect...");
- if (ConnectNamedPipe(hPipe, IntPtr.Zero) == 0)
- {
- Console.WriteLine("Error connecting to client: " + Marshal.GetLastWin32Error());
- return;
- }
- Console.WriteLine("Client connected.");
- // Get the standard output handle
- IntPtr hStdOut = GetStdHandle(-11); // STD_OUTPUT_HANDLE
- // Read user input from the console and send it to the named pipe
- while (true)
- {
- Console.Write("Enter text to send to client (or 'exit' to quit): ");
- string input = Console.ReadLine();
- if (input.ToLower() == "exit")
- break;
- byte[] buffer = Encoding.ASCII.GetBytes(input);
- uint bytesWritten;
- if (WriteFile(hPipe, buffer, (uint)buffer.Length, out bytesWritten, IntPtr.Zero) == 0)
- {
- Console.WriteLine("Error writing to pipe: " + Marshal.GetLastWin32Error());
- break;
- }
- }
- // Close the named pipe and exit
- CloseHandle(hPipe);
- Console.WriteLine("Named pipe closed.");
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement