Exemplo n.º 1
0
        /// <summary>Attempts to obtain an exclusive lock within amount
        /// of time given. Currently polls once per second until
        /// lockWaitTimeout is passed.
        /// </summary>
        /// <param name="lockWaitTimeout">length of time to wait in ms
        /// </param>
        /// <returns> true if lock was obtained
        /// </returns>
        /// <throws>  IOException if lock wait times out or obtain() throws an IOException </throws>
        public virtual bool Obtain(long lockWaitTimeout)
        {
            int  sleepCount    = 0;
            bool locked        = Obtain();
            int  maxSleepCount = (int)(lockWaitTimeout / LOCK_POLL_INTERVAL);

            maxSleepCount = System.Math.Min(maxSleepCount, 1);

            while (!locked)
            {
                FSDirectory.Log("Lock.Obtain timeout: sleepcount = {0} (timeout={1},maxsleepcount={2})", sleepCount, lockWaitTimeout, maxSleepCount);
                if (sleepCount++ == maxSleepCount)
                {
                    // Try and be a little more verbose on failure
                    string lockpath = this.ToString();
                    System.Text.StringBuilder ex = new System.Text.StringBuilder();
                    ex.Append("Lock obtain timed out: ");
                    ex.Append(lockpath);
                    if (System.IO.File.Exists(lockpath))
                    {
                        System.IO.FileStream   fs = System.IO.File.Open(lockpath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                        System.IO.StreamReader sr = new System.IO.StreamReader(fs);
                        string pid = sr.ReadToEnd().Trim();
                        sr.Close();
                        fs.Close();
                        ex.Append(" -- pid ").Append(pid);

                        if (pid == String.Empty)
                        {
                            ex.Append("(empty)");
                        }
                        else if (System.IO.Directory.Exists("/proc/" + pid))
                        {
                            ex.Append(" -- process exists");
                        }
                        else
                        {
                            ex.Append(" -- process does not exist, stale lockfile?");
                        }
                    }
                    else
                    {
                        ex.Append(" -- lock file doesn't exist!?");
                    }
                    throw new System.IO.IOException(ex.ToString());
                }
                System.Threading.Thread.Sleep((int)LOCK_POLL_INTERVAL);
                locked = Obtain();
            }
            return(locked);
        }