Esempio n. 1
0
        static void Main(string[] args)
        {
            SafeMailslotHandle hMailslot = null;

            try
            {
                // Prepare the security attributes (the lpSecurityAttributes parameter
                // in CreateMailslot) for the mailslot. This is optional. If the
                // lpSecurityAttributes parameter of CreateMailslot is NULL, the
                // mailslot gets a default security descriptor and the handle cannot
                // be inherited. The ACLs in the default security descriptor of a
                // mailslot grant full control to the LocalSystem account, (elevated)
                // administrators, and the creator owner. They also give only read
                // access to members of the Everyone group and the anonymous account.
                // However, if you want to customize the security permission of the
                // mailslot, (e.g. to allow Authenticated Users to read from and
                // write to the mailslot), you need to create a SECURITY_ATTRIBUTES
                // structure.
                SECURITY_ATTRIBUTES sa = null;
                sa = CreateMailslotSecurity();

                // Create the mailslot.
                hMailslot = NativeMethod.CreateMailslot(
                    MailslotName,               // The name of the mailslot
                    0,                          // No maximum message size
                    MAILSLOT_WAIT_FOREVER,      // Waits forever for a message
                    sa                          // Mailslot security attributes
                    );

                if (hMailslot.IsInvalid)
                {
                    throw new Win32Exception();
                }

                Console.WriteLine("The mailslot ({0}) is created.", MailslotName);

                // Check messages in the mailslot.
                Console.Write("Press ENTER to check new messages or press Q to quit ...");
                string cmd = Console.ReadLine();
                while (!cmd.Equals("Q", StringComparison.OrdinalIgnoreCase))
                {
                    Console.WriteLine("Checking new messages...");
                    ReadMailslot(hMailslot);

                    Console.Write("Press ENTER to check new messages or press Q to quit ...");
                    cmd = Console.ReadLine();
                }
            }
            catch (Win32Exception ex)
            {
                Console.WriteLine("The server throws the error: {0}", ex.Message);
            }
            finally
            {
                if (hMailslot != null)
                {
                    hMailslot.Close();
                    hMailslot = null;
                }
            }
        }