Win32 API与.NET Framework的对应表

Atom Functions

Win32 function Description .NET Framework API
AddAtom Adds a character string to the local atom table. System.String.Intern

Note   String is not exactly an atom.

FindAtom Searches the local atom table for the specified character string. System.String.IsInterned

Note   String is not exactly an atom.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Bitmap Functions

Win32 function Description .NET Framework API
AlphaBlend Displays a bitmap with transparent or semitransparent pixels. System.Drawing.Graphics.DrawImage
BitBlt Performs a bit-block transfer. System.Drawing.Graphics.DrawImage
CreateBitmap Creates a bitmap. System.Drawing.Bitmap constructor

Note   Creates a DIB, not a DDB.

GetBitmapDimensionEx Gets the dimensions of a bitmap. System.Drawing.Bitmap.Size
GetDIBColorTable Retrieves RGB color values from a DIB section bitmap. System.Drawing.Bitmap.Palette
GetDIBits Copies a bitmap into a buffer. System.Drawing.Bitmap.LockBits
GetPixel Gets the RGB color value of the pixel at a given coordinate. System.Drawing.Bitmap.GetPixel
GradientFill Fills rectangle and triangle structures. System.Drawing.Graphics.FillRectangle(Drawing2D.LinearGradiantBrush, Rectangle)
LoadBitmap Loads a bitmap from a module's executable file. System.Drawing.Bitmap.Bitmap(Type, String)
SetPixel Sets the color for a pixel. System.Drawing.Bitmap.SetPixel
SetPixelV Sets a pixel to the best approximation of a color. System.Drawing.Bitmap.SetPixel(…, Graphics.GetNearestColor(Color))
StretchBlt Copies a bitmap and stretches or compresses it. System.Drawing.Graphics.DrawImage

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Brush Functions

Win32 function Description .NET Framework API
CreateBrushIndirect Creates a brush with a specified style, color, and pattern. Any of the following:
System.Drawing.Brushes
System.Drawing.SolidBrush
System.Drawing.TextureBrush
System.Drawing.Drawing2D.HatchBrush
System.Drawing.Drawing2D.LinearGradientBrush
System.Drawing.Drawing2D.PathGradientBrush
CreateHatchBrush Creates a brush with a hatch pattern and color. System.Drawing.Drawing2D.HatchBrush constructor
CreatePatternBrush Creates a brush with a bitmap pattern. System.Drawing.TextureBrush constructor
CreateSolidBrush Creates a brush with a solid color. System.Drawing.SolidBrush constructor
GetSysColorBrush Gets a handle for a brush that corresponds to a color index. System.Drawing.Brushes class

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Button Functions

Win32 function Description .NET Framework API
CheckDlgButton Changes the check state of a button control. System.Windows.Forms.CheckBox.Checked
CheckRadioButton Adds a check mark to a specified radio button in a group and removes a check mark from all other radio buttons in the group. System.Windows.Forms.RadioButton.Checked
IsDlgButtonChecked Determines whether a button control has a check mark next to it or whether a three-state button control is grayed, checked, or neither. System.Windows.Forms.CheckBox.CheckState

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Clipboard Functions

Win32 function Description .NET Framework API
CountClipboardFormats Retrieves the number of different data formats currently on the clipboard. System.Windows.Forms.DataObject.GetFormats
EnumClipboardFormats Enumerates the data formats currently available on the clipboard. System.Windows.Forms.DataObject.GetFormats
GetClipboardData Retrieves data from the clipboard in a specified format. System.Windows.Forms.ClipBoard.GetDataObject
IsClipboardFormatAvailable Determines whether the clipboard contains data in the specified format. System.Windows.Forms.DataObject.GetDataPresent
RegisterClipboardFormat Registers a new clipboard format. System.Windows.Forms.DataFormats.GetFormat
SetClipboardData Places data on the clipboard in a specified clipboard format. System.Windows.Forms.ClipBoard.SetDataObject

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Clipping Functions

Win32 function Description .NET Framework API
ExcludeClipRect Creates a new clipping region that consists of the existing clipping region minus the specified rectangle. System.Drawing.Graphics.ExcludeClip
ExtSelectClipRgn Combines the specified region with the current clipping region using the specified mode. System.Drawing.Graphics.SetClip
GetClipBox Retrieves the dimensions of the tightest bounding rectangle that can be drawn around the current visible area on the device. System.Drawing.Graphics.VisibleClipBounds
GetClipRgn Retrieves a handle identifying the current application-defined clipping region for the specified device context. System.Drawing.Graphics.Clip
IntersectClipRect Creates a new clipping region from the intersection of the current clipping region and the specified rectangle. System.Drawing.Graphics.IntersectClip
OffsetClipRgn Moves the clipping region of a device context by the specified offsets. System.Drawing.Graphics.TranslateClip
PtVisible Determines whether the specified point is within the clipping region of a device context. System.Drawing.Graphics.IsVisible
RectVisible Determines whether any part of the specified rectangle lies within the clipping region of a device context. System.Drawing.Graphics.IsVisible
SelectClipPath Selects the current path as a clipping region for a device context, combining the new region with any existing clipping region by using the specified mode. System.Drawing.Graphics.SetClip
SelectClipRgn Selects a region as the current clipping region for the specified device context. System.Drawing.Graphics.Clip

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Color Functions

Win32 function Description .NET Framework API
CreateHalftonePalette Creates a halftone palette for the specified device context. System.Drawing.Graphics.GetHalftonePalette
CreatePalette Creates a logical palette. System.Drawing.Image.Palette
GetNearestColor Retrieves a color value identifying a color from the system palette that will be displayed when the specified color value is used. System.Drawing.Graphics.GetNearestColor
GetPaletteEntries Retrieves a specified range of palette entries from the given logical palette. System.Drawing.Image.Palette.Entries

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Combo Box Functions

Win32 function Description .NET Framework API
DlgDirListComboBox Replaces the contents of a combo box with the names of specified subdirectories and files. System.Windows.Forms.ComboBox.Items.AddRange(System.IO.Directory.GetFileSystemEntries)
DlgDirSelectComboBoxEx Retrieves the current selection from a combo box filled by using DlgDirListComboBox. System.Windows.Forms.ComboBox.SelectedItem
GetComboBoxInfo Retrieves information about a specified combo box. System.Windows.Forms.ComboBox properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Common Dialog Box Functions

Win32 function Description .NET Framework API
ChooseColor Creates a Color dialog box that enables the user to select a color. System.Windows.Forms.ColorDialog constructor

Note   Dialog cannot be modified through a hook.

ChooseFont Creates a Font dialog box that enables the user to choose attributes for a logical font. System.Windows.Forms.FontDialog constructor

Note   Dialog cannot be modified through a hook.

GetFileTitle Retrieves the name of the specified file. System.IO.FileInfo.Name

Note   Does not take user preferences into account.

GetOpenFileName Creates an Open dialog box that lets the user specify the drive, directory, and name of a file or set of files to open. System.Windows.Forms.OpenFileDialog.ShowDialog

Note   Dialog cannot be modified through a hook.

GetSaveFileName Creates a Save dialog box that lets the user specify the drive, directory, and name of a file to save. System.Windows.Forms.SaveFileDialog.ShowDialog

Note   Dialog cannot be modified through a hook.

PageSetupDlg Creates a Page Setup dialog box that enables the user to specify the attributes of a printed page. System.Windows.Forms.PageSetupDialog.ShowDialog

Note   Dialog cannot be modified through a hook.

PrintDlg Displays a Print dialog box. System.Windows.Forms.PrintDialog.ShowDialog

Note   Dialog cannot be modified through a hook.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Console Functions

Win32 function Description .NET Framework API
GetStdHandle Retrieves a handle for the standard input, standard output, or standard error device. System.Console.OpenStandardIn
System.Console.OpenStandardOut
System.Console.OpenStandardError
ReadConsole Reads character input from the console input buffer and removes it from the buffer. System.Console.Read
SetStdHandle Sets the handle for the standard input, standard output, or standard error device. System.Console.SetIn
System.Console.SetOut
System.Console.SetError
WriteConsole Writes a character string to a console screen buffer beginning at the current cursor location. System.Console.Write

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Coordinate Functions

Win32 function Description .NET Framework API
ClientToScreen Converts the client-area coordinates of a specified point to screen coordinates. System.Windows.Forms.Form.PointToScreen
CombineTransform Concatenates two world-space to page-space transformations. System.Drawing.Drawing2D.Matrix.Multiply
DPtoLP Converts device coordinates into logical coordinates. System.Drawing.Graphics.TransformPoints
GetMapMode Retrieves the current mapping mode. System.Drawing.Graphics.PageUnit
GetWindowExtEx Retrieves the x-extent and y-extent of the window for the specified device context. System.Drawing.Graphics.PageScale
GetWindowOrgEx Retrieves the x-coordinates and y-coordinates of the window origin for the specified device context. System.Drawing.Graphics.Transform.OffsetX
System.Drawing.Graphics.Transform.OffsetY
GetWorldTransform Retrieves the current world-space to page-space transformation. System.Drawing.Graphics.Transform
LPtoDP Converts logical coordinates into device coordinates. System.Drawing.Graphics.TransformPoints
ModifyWorldTransform Changes the world transformation for a device context using the specified mode. System.Drawing.Graphics.Transform
OffsetViewportOrgEx Modifies the viewport origin for a device context using the specified horizontal and vertical offsets. System.Drawing.Graphics.TranslateTransform
OffsetWindowOrgEx Modifies the window origin for a device context using the specified horizontal and vertical offsets. System.Drawing.Graphics.TranslateTransform
ScreenToClient Converts the screen coordinates of a specified point on the screen-to-client coordinates. System.Windows.Forms.Form.PointToClient
SetMapMode Sets the mapping mode of the specified device context. System.Drawing.Graphics.PageUnit
SetWindowExtEx Sets the horizontal and vertical extents of the window for a device context by using the specified values. System.Drawing.Graphics.PageScale
Drawing.Graphics.ScaleTransform
SetWindowOrgEx Specifies which window point maps to the viewport origin (0,0). System.Drawing.Graphics.TranslateTransform
SetWorldTransform Sets a two-dimensional linear transformation between world space and page space for the specified device context. System.Drawing.Graphics.Transform

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Cursor Functions

Win32 function Description .NET Framework API
ClipCursor Confines the cursor to a rectangular area on the screen. System.Windows.Forms.Cursor.Clip
CopyCursor Copies the specified cursor. System.Windows.Forms.Cursor.CopyHandle
CreateCursor Creates a cursor having the specified size, bit patterns, and hot spot. System.Windows.Forms.Cursor constructor
System.Windows.Forms.Cursor.Size
System.Windows.Forms.Cursor.Position
DestroyCursor Destroys a cursor. System.Windows.Forms.Cursor.Dispose
GetClipCursor Retrieves the screen coordinates of the rectangular area to which the cursor is confined. System.Windows.Forms.Cursor.Clip
GetCursor Retrieves a handle to the current cursor. System.Windows.Forms.Cursor.Handle
GetCursorInfo Retrieves information about the global cursor. System.Windows.Forms.Cursor.Position
System.Windows.Forms.SystemInformation.CursorSize
GetCursorPos Retrieves the cursor's position. System.Windows.Forms.Control.MousePosition
System.Windows.Forms.Cursor.Position
LoadCursor Loads a cursor resource from an executable file. System.Windows.Forms.Cursor constructor
LoadCursorFromFile Creates a cursor based on data contained in a file. System.Windows.Forms.Cursor constructor
SetCursor Sets the cursor shape. System.Windows.Forms.Cursor.Current
SetCursorPos Moves the cursor to the specified screen coordinates. System.Windows.Forms.Cursor.Position
ShowCursor Displays or hides the cursor. System.Windows.Forms.Cursor.Show
Windows.Forms.Cursor.Hide

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Debugging Functions

Win32 function Description .NET Framework API
DebugActiveProcess Enables a debugger to attach to an active process and debug it. System.Diagnostics.Debugger.Launch
DebugBreak Causes a breakpoint exception to occur in the current process. System.Diagnostics.Debugger.Break
IsDebuggerPresent Determines whether the calling process is running under the context of a debugger. System.Diagnostics.Debugger.IsAttached
OutputDebugString Sends a string to the debugger for display. System.Diagnostics.Debugger.Log

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Device Context Functions

Win32 function Description .NET Framework API
ChangeDisplaySettings Changes the settings of the default display device to the specified graphics mode. System.Management.ManagementClass("Win32_VideoController")
ChangeDisplaySettingsEx Changes the settings of the specified display device to the specified graphics mode. System.Management.ManagementClass("Win32_VideoController")
DeviceCapabilities Retrieves the capabilities of a printer device driver. System.Drawing.Printing.PageSettings
System.Drawing.Printing.PrinterSettings
EnumDisplayDevices Retrieves information about the display devices in a system. System.Management.ManagementClass("Win32_DesktopMonitor")
EnumDisplaySettings Retrieves information about one of the graphics modes for a display device. System.Management.ManagementClass("CIM_VideoControllerResolution")
GetDC Retrieves a handle to a display device context for the client area of a specified window or for the entire screen. To retrieve a Graphics object, use any of the following:
System.Drawing.Graphics.FromHwnd(Windows.Forms.Control.Handle)
System.Drawing.Printing.PrintPageEventArgs.Graphics
System.Windows.Forms.PaintEventArgs.Graphics

To explicitly retrieve a handle, use the following:
System.Drawing.Graphics.GetHdc

GetDCEx Retrieves a handle to a display device context for the client area of a specified window or for the entire screen. To retrieve a Graphics object, use any of the following:
System.Drawing.Graphics.FromHwnd(Windows.Forms.Control.Handle)
System.Drawing.Printing.PrintPageEventArgs.Graphics
System.Windows.Forms.PaintEventArgs.Graphics

To explicitly retrieve a handle, use the following:
System.Drawing.Graphics.GetHdc

GetDeviceCaps Retrieves device-specific information for the specified device. System.Drawing.Graphics properties
System.Drawing.Printing.PrinterSettings
System.Management classes
GetLayout Retrieves the layout of a device context. System.Windows.Forms.Control.RightToLeft
GetObject Retrieves information for the specified graphics object. System.Drawing.Bitmap properties
System.Drawing.Brush properties
System.Drawing.Font properties
System.Drawing.Pen properties
GetObjectType Retrieves the type of the specified object. System.Object.GetType
GetStockObject Retrieves a handle to one of the stock pens, brushes, fonts, or palettes. System.Drawing.Brushes
System.Drawing.Pens
ReleaseDC Releases a device context, freeing it for use by other applications. System.Drawing.Graphics.ReleaseHdc
SetLayout Sets the layout for a device context. System.Windows.Forms.Control.RightToLeft = System.Windows.Forms.RightToLeft.Yes

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Dialog Box Functions

Win32 function Description .NET Framework API
CreateDialog Creates a modeless dialog box from a dialog box template resource. System.Windows.Forms.Form constructor
System.Windows.Forms.Form properties
CreateDialogIndirect Creates a modeless dialog box from a dialog box template in memory. System.Windows.Forms.Form constructor
System.Windows.Forms.Form properties
DefDlgProc Calls the default dialog box window procedure to provide default processing for any window messages that a dialog box with a private window class does not process. System.Windows.Forms.Form.DefWndProc
DialogBox Creates a modal dialog box from a dialog box template resource. System.Windows.Forms.Form constructor
System.Windows.Forms.Form.ShowDialog
DialogBoxIndirect Creates a modal dialog box from a dialog box template in memory. System.Windows.Forms.Form constructor
System.Windows.Forms.Form.ShowDialog
DialogProc An application-defined callback function used with the CreateDialog and DialogBox families of functions. System.Windows.Forms.Form.WndProc
EndDialog Destroys a modal dialog box. System.Windows.Forms.Form.Close
GetDlgCtrlID Retrieves the identifier of the specified control. System.Windows.Forms.Form.Controls.IndexOf
GetDlgItem Retrieves a handle to a control in the specified dialog box. System.Windows.Forms.Form.Controls.Item
GetDlgItemInt Translates the text of a specified control in a dialog box into an integer value. System.Int32.Parse(Form.Text)
System.UInt32.Parse(Form.Text)
GetDlgItemText Retrieves the title or text associated with a control in a dialog box. System.Windows.Forms.Form.Controls.Item[].Text
GetNextDlgGroupItem Retrieves a handle to the first control in a group of controls that precedes (or follows) the specified control. Iterate through the controls:
System.Windows.Forms.Form.Controls.Item

Remember to determine whether the control is active by referencing the Enabled and Visible properties of the control.

Note   The order that the controls are presented in might not be the same order in which GetNextDlgGroupItem presents the controls.

GetNextDlgTabItem Retrieves a handle to the first control that has the WS_TABSTOP style that precedes (or follows) the specified control. Iterate through the controls:
System.Windows.Forms.Form.Controls.Item

Remember to determine whether the control is active by referencing the Enabled, Visible, and TabStop properties of the control.

Note   The order that the controls are presented in might not be the same order in which GetNextDlgGroupItem presents the controls.

MessageBox Creates, displays, and operates a message box. System.Windows.Forms.MessageBox.Show
MessageBoxEx Creates, displays, and operates a message box. System.Windows.Forms.MessageBox.Show
MessageBoxIndirect Creates, displays, and operates a message box. System.Windows.Forms.MessageBox.Show
SendDlgItemMessage Sends a message to the specified control in a dialog box. System.Windows.Forms.Form.WndProc(System.Windows.Forms.Message)
SetDlgItemInt Sets the text of a control in a dialog box to the string representation of a specified integer value. System.Windows.Forms.Control.Text = System.Int32.ToString
SetDlgItemText Sets the title or text of a control in a dialog box. System.Windows.Forms.Control.Text

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Dynamic-Link Library Functions

Win32 function Description .NET Framework API
GetModuleFileName Retrieves the full path and file name for the file containing the specified module. System.Reflection.Module.FullyQualifiedName
GetModuleHandle Retrieves a module handle for the specified module. System.Runtime.InteropServices.Marshal.GetHINSTANCE
LoadLibrary Maps the specified executable module into the address space of the calling process. Any of the following:
System.Reflection.Assembly.Load
System.Reflection.Assembly.LoadFrom
System.Reflection.Assembly.LoadWithPartialName
LoadLibraryEx Maps the specified executable module into the address space of the calling process. Any of the following:
System.Reflection.Assembly.Load
System.Reflection.Assembly.LoadFrom
System.Reflection.Assembly.LoadWithPartialName

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Error Handling Functions

Win32 function Description .NET Framework API
FatalAppExit Displays a message box and terminates the application when the message box is closed. System.Windows.Forms.MessageBox.Show
System.Diagnostics.Process.Kill
GetLastError Retrieves the calling thread's last-error code value. System.Runtime.InteropServices.Marshall.GetLastWin32Error

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Event Logging Functions

Win32 function Description .NET Framework API
ClearEventLog Clears the specified event log, and optionally saves the current copy of the log file to a backup file. System.Diagnostics.EventLog.Clear
CloseEventLog Closes a read handle to the specified event log. System.Diagnostics.EventLog.Close
DeregisterEventSource Closes a write handle to the specified event log. System.Diagnostics.EventLog.DeleteEventSource
GetNumberOfEventLogRecords Retrieves the number of records in the specified event log. System.Diagnostics.EventLog.Entries.Count
GetOldestEventLogRecord Retrieves the absolute record number of the oldest record in the specified event log. System.Diagnostics.EventLogEntryCollection[0]
System.Diagnostics.EventLogEntry.TimeWritten
NotifyChangeEventLog Enables an application to receive notification when an event is written to the specified event log file. System.Diagnostics.EventLog.EnableRaisingEvents
OpenBackupEventLog Opens a handle to a backup event log. System.Diagnostics.EventLog constructor
OpenEventLog Opens a handle to an event log. System.Diagnostics.EventLog constructor
ReadEventLog Reads a whole number of entries from the specified event log. System.Diagnostics.EventLogEntryCollection.CopyTo
RegisterEventSource Retrieves a registered handle to an event log. System.Diagnostics.EventLog.CreateEventSource
ReportEvent Writes an entry at the end of the specified event log. System.Diagnostics.EventLog.WriteEntry

Alphabetical Win32 Category List
Hierarchical Win32 Category List

File I/O Functions

Win32 function Description .NET Framework API
CopyFile Copies an existing file to a new file. Either of the following:
System.IO.File.Copy
IO.FileInfo.CopyTo
CreateDirectory Creates a new directory. Any of the following:
System.IO.Directory.CreateDirectory
System.IO.Directory.CreateSubdirectory
System.IO.DirectoryInfo.Create
CreateFile Creates or opens a file object. System.IO.File class and System.IO.FileInfo class
DeleteFile Deletes an existing file. Any of the following:
System.IO.Directory.Delete
System.IO.DirectoryInfo.Delete
System.IO.File.Delete
System.IO.FileInfo.Delete
FileIOCompletionRoutine An application-defined callback function used with ReadFileEx and WriteFileEx. User defined.
FindClose Closes the specified search handle. See FindFirstFile and FindNextFile
FindCloseChangeNotification Stops change notification handle monitoring. System.IO.FileSystemWatcher.EnableRaisingEvents
FindFirstChangeNotification Creates a change notification handle. System.IO.FileSystemWatcher class
FindFirstFile Searches a directory for a file whose name matches the specified file name. Any of the following:
System.IO.Directory.Exists
System.IO.Directory.GetDirectories
System.IO.Directory.GetFileSystemEntries
System.IO.Directory.GetFiles
System.IO.DirectoryInfo.Exists
System.IO.DirectoryInfo.GetDirectories
System.IO.DirectoryInfo.GetFileSystemInfos
System.IO.DirectoryInfo.GetFiles
System.IO.File.Exists
System.IO.FileInfo.Exists
FindFirstFileEx Searches a directory for a file whose name and attributes match the specified file name. Same as FindFirstFile
FindNextChangeNotification Requests that the operating system signal a change notification handle the next time it detects an appropriate change. System.IO.FileSystemWatcher class
FindNextFile Continues a file search. Any of the following:
System.IO.Directory.GetDirectories
System.IO.Directory.GetFileSystemEntries
System.IO.Directory.GetFiles
System.IO.DirectoryInfo.GetDirectories
System.IO.DirectoryInfo.GetFileSystemInfos
System.IO.DirectoryInfo.GetFiles
FlushFileBuffers Clears the buffers for the specified file and causes all buffered data to be written to the file. System.IO.FileStream.Flush
GetBinaryType Determines whether a file is executable. System.IO.FileSystemInfo.Extension

Note   Only manipulates strings; does not do a file-system check.

GetCurrentDirectory Retrieves the current directory for the current process. System.IO.Directory.GetCurrentDirectory
GetDriveType Determines whether a disk drive is a removable, fixed, CD-ROM, RAM disk, or network drive. System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"").Get
System.Management.ManagementObject.Properties
System.IO.DriveInfo.DriveType
GetFileAttributes Retrieves attributes for a specified file or directory. Any of the following:
System.IO.Directory.GetAttributes
System.IO.File.GetAttributes
System.IO.FileSystemInfo.Attributes
GetFileAttributesEx Retrieves attributes for a specified file or directory. Any of the following:
System.IO.Directory.GetAttributes
System.IO.File.GetAttributes
System.IO.FileSystemInfo.Attributes
GetFileInformationByHandle Retrieves file information for a specified file. System.IO.FileInfo properties
GetFileSize Retrieves the size of a specified file. Either of the following:
System.IO.FileInfo.Length
System.IO.FileStream.Length
GetFileSizeEx Retrieves the size of a specified file. Either of the following:
System.IO.FileInfo.Length
System.IO.FileStream.Length
GetFullPathName Retrieves the full path and file name of a specified file. Either of the following:
System.IO.FileSystemInfo.FullName
System.IO.Path.GetFullPath
GetTempFileName Creates a name for a temporary file. System.IO.Path.GetTempFileName
GetTempPath Retrieves the path of the directory designated for temporary files. System.IO.Path.GetTempPath
LockFile Locks a region in an open file. System.IO.FileStream.Lock
LockFileEx Locks a region in an open file for shared or exclusive access. System.IO.FileStream.Lock
MoveFile Moves an existing file or a directory. Any of the following:
System.IO.Directory.Move
System.IO.DirectoryInfo.MoveTo
System.IO.File.Move
System.IO.FileInfo.MoveTo
ReadDirectoryChangesW Retrieves information describing the changes occurring within a directory. System.IO.FileSystemWatcher class
ReadFile Reads data from a file, starting at the specified position. Any of the following:
System.IO.FileStream.BeginRead/EndRead
System.IO.FileStream.Read
System.IO.FileStream.ReadByte
ReadFileEx Reads data from a file asynchronously. System.IO.FileStream.BeginRead/EndRead
RemoveDirectory Deletes an existing empty directory. Either of the following:
System.IO.Directory.Delete
System.IO.DirectoryInfo.Delete
SearchPath Searches for the specified file. Any of the following:
System.IO.Directory.Exists
System.IO.Directory.GetDirectories
System.IO.Directory.GetFileSystemEntries
System.IO.Directory.GetFiles
System.IO.DirectoryInfo.Exists
System.IO.DirectoryInfo.GetDirectories
System.IO.DirectoryInfo.GetFileSystemInfos
System.IO.DirectoryInfo.GetFiles
System.IO.File.Exists
System.IO.FileInfo.Exists
SetCurrentDirectory Changes the current directory for the current process. System.IO.Directory.SetCurrentDirectory
SetEndOfFile Moves the end-of-file position for the specified file. System.IO.FileStream.SetLength
SetFileAttributes Sets the attributes for a file. System.IO.File.SetAttributes
SetFilePointer Moves the file pointer of an open file. Either of the following:
System.IO.FileStream.Position
System.IO.FileStream.Seek
SetFilePointerEx Moves the file pointer of an open file. Either of the following:
System.IO.FileStream.Position
System.IO.FileStream.Seek
UnlockFile Unlocks a previously locked region in an open file. System.IO.FileStream.Unlock
UnlockFileEx Unlocks a previously locked region in an open file. System.IO.FileStream.Unlock
WriteFile Writes data to a file. Any of the following:
System.IO.FileStream.BeginWrite and EndWrite
System.IO.FileStream.Write
System.IO.FileStream.WriteByte
System.IO.BinaryWriter.Write
WriteFileEx Writes data to a file asynchronously. System.IO.FileStream.BeginWrite and EndWrite

Alphabetical Win32 Category List
Hierarchical Win32 Category List

File System Functions

Used with file systems:

Win32 function Description .NET Framework API
GetDiskFreeSpace Retrieves information about the specified disk, including the amount of free space on the disk. System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"").Get
System.Management.ManagementObject.Properties
GetDiskFreeSpaceEx Retrieves information about the specified disk, including the amount of free space on the disk. System.Management.ManagementObject("Win32_LogicalDisk.DeviceID=\"C:\"").Get
System.Management.ManagementObject.Properties
GetLogicalDriveStrings Fills a buffer with strings that specify valid drives in the system. Either of the following:
System.Environment.GetLogicalDrives
System.IO.Directory.GetLogicalDrives

Used with an encrypted file system:

Win32 function Description .NET Framework API
DecryptFile Decrypts an encrypted file or directory. System.Security.Cryptography.CryptoStream.Read
EncryptFile Encrypts a file or directory. System.Security.Cryptography.CryptoStream.Write
FileEncryptionStatus Retrieves the encryption status of the specified file. System.IO.FileSystemInfo.Attributes

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Filled Shape Functions

Win32 function Description .NET Framework API
Chord Draws an area bounded by an ellipse and a line segment. System.Drawing.Graphics.DrawArc
System.Drawing.Graphics.DrawLine
Ellipse Draws an ellipse. System.Drawing.Graphics.DrawEllipse
System.Drawing.Graphics.FillEllipse
FillRect Fills a rectangle using a brush. System.Drawing.Graphics.FillRectangle
InvertRect Inverts the color values of the pixels in a rectangle. System.Windows.Forms.ControlPaint.DrawReversibleFrame
System.Windows.Forms.ControlPaint.DrawReversibleLine
Pie Draws a pie-shaped wedge bounded by an ellipse and two radials. System.Drawing.Graphics.DrawPie
System.Drawing.Graphics.FillPie
Polygon Draws a polygon. System.Drawing.Graphics.DrawPolygon
System.Drawing.Graphics.FillPolygon
Rectangle Draws a rectangle. System.Drawing.Graphics.DrawRectangle
System.Drawing.Graphics.FillRectangle
RoundRect Draws a rectangle with rounded corners. System.Drawing.Drawing2D.GraphicsPath.AddLines
System.Drawing.Pen.LineJoin = System.Drawing.Pen.LineJoin.Round
System.Drawing.Graphics.DrawPath
System.Drawing.Graphics.FillPath

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Font and Text Functions

Win32 function Description .NET Framework API
AddFontMemResourceEx Adds an embedded font to the system font table. System.Drawing.Text.PrivateFontCollection.AddMemoryFont
AddFontResourceEx Adds a private or non-enumerable font to the system font table. System.Drawing.Text.PrivateFontCollection.AddFontFile
CreateFont Creates a logical font. System.Drawing.Font constructor
DrawText Draws formatted text in a rectangle. System.Drawing.Graphics.DrawString
DrawTextEx Draws formatted text in a rectangle. System.Drawing.Graphics.DrawString
EnumFontFamExProc An application-defined callback function used with EnumFontFamiliesEx to process fonts. System.Drawing.Text.InstalledFontCollection.Families
EnumFontFamiliesEx Enumerates all fonts in the system with certain characteristics. System.Drawing.Text.InstalledFontCollection.Families
ExtTextOut Draws a character string. System.Drawing.Graphics.DrawString
GetCharABCWidths Gets the widths of consecutive characters from the TrueType font. Get a Region[] for the characters:
System.Drawing.Graphics.MeasureCharacterRanges;

Determine the width of each Region:
System.Drawing.Rectangle.Round(Region.GetBounds).Width

GetCharABCWidthsFloat Gets the widths of consecutive characters from the current font. Get a Region[] for the characters:
System.Drawing.Graphics.MeasureCharacterRanges;

Determine the width of each Region:
System.Drawing.Region.GetBounds.Width

GetCharWidth32 Gets the widths of consecutive characters from the current font. Get a Region[] for the characters:
System.Drawing.Graphics.MeasureCharacterRanges;

Determine the width of each Region:
System.Drawing.Rectangle.Round(Region.GetBounds).Width

GetCharWidthFloat Gets the fractional widths of consecutive characters from the current font. Get a Region[] for the characters:
System.Drawing.Graphics.MeasureCharacterRanges;

Determine the width of each Region:
System.Drawing.Region.GetBounds.Width

GetOutlineTextMetrics Gets text metrics for TrueType fonts. System.Drawing.Font properties
GetTabbedTextExtent Computes the width and height of a character string, including tabs. System.Drawing.Graphics.MeasureString
GetTextAlign Gets the text-alignment setting for a device context. System.Drawing.StringFormat.Alignment
System.Drawing.StringFormat.LineAlignment
GetTextColor Gets the text color for a device context. System.Drawing.SolidBrush.Color
GetTextExtentPoint32 Computes the width and height of a string of text. System.Drawing.Graphics.MeasureString
GetTextFace Gets the name of the font that is selected into a device context. System.Drawing.Font.Name
GetTextMetrics Fills a buffer with the metrics for a font. System.Drawing.Font properties
RemoveFontMemResourceEx Removes a font whose source was embedded in a document from the system font table. System.Drawing.Text.PrivateFontCollection.Dispose
RemoveFontResourceEx Removes a private or non-enumerable font from the system font table. System.Drawing.Text.PrivateFontCollection.Dispose
SetTextAlign Sets the text-alignment flags for a device context. System.Drawing.StringFormat.Alignment
System.Drawing.StringFormat.LineAlignment
SetTextColor Sets the text color for a device context. Either of the following:
System.Drawing.Brushes
System.Drawing.SolidBrush.SolidBrush(Color)
TabbedTextOut Writes a character string at a location, expanding tabs to specified values. System.Drawing.Graphics.DrawString using System.Drawing.StringFormat.SetTabStops
TextOut Writes a character string at a location. System.Drawing.Graphics.DrawString

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Icon Functions

Win32 function Description .NET Framework API
CopyIcon Copies an icon from another module. System.Drawing.Icon.FromHandle
CreateIcon Creates an icon with a specified size, color, and bit pattern. System.Drawing.Icon constructor
DestroyIcon Destroys an icon. System.Drawing.Icon.Dispose
DrawIcon Draws an icon. System.Drawing.Graphics.DrawIcon
DuplicateIcon Creates a duplicate of a specified icon. System.Drawing.Icon.Clone
LoadIcon Loads an icon from the executable file associated with an application. System.Drawing.Icon constructor

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Input Method Editor Functions

Win32 function Description .NET Framework API
ImmAssociateContext Associates the specified input context with the specified window. Either of the following:
System.Windows.Forms.Control.DefaultImeMode
System.Windows.Forms.Control.ImeMode
ImmAssociateContextEx Changes the association between the input method context and the specified window or its children. Any of the following:
System.Windows.Forms.Control.DefaultImeMode
System.Windows.Forms.Control.ImeMode
System.Windows.Forms.Control.ResetImeMode
ImmDisableIME Disables the Input Method Editor. System.Windows.Forms.Control.ImeMode = System.Windows.Forms.ImeMode.Disable
ImmGetContext Retrieves the input context associated with the specified window. System.Windows.Forms.Control.ImeMode

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Keyboard Accelerator Functions

Win32 function Description .NET Framework API
TranslateAccelerator Processes accelerator keys for menu commands. System.Windows.Forms.MenuItem.Shortcut

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Keyboard Input Functions

Win32 function Description .NET Framework API
ActivateKeyboardLayout Sets the input locale identifier for the calling thread or the current process. System.Windows.Forms.InputLanguage.CurrentInputLanguage
EnableWindow Enables or disables mouse and keyboard input to the specified window or control. System.Windows.Forms.Control.Enabled
GetActiveWindow Retrieves the window handle to the active window attached to the calling thread's message queue. System.Windows.Forms.Form.ActiveForm
GetFocus Retrieves the handle to the window that has the keyboard focus. System.Windows.Forms.Control.Controls[].Focused
GetKeyboardLayout Retrieves the active input locale identifier for the specified thread. System.Windows.Forms.InputLanguage.CurrentInputLanguage
GetKeyboardLayoutList Retrieves the input locale identifiers corresponding to the current set of input locales in the system. System.Windows.Forms.InputLanguage.InstalledInputLanguages
GetKeyboardLayoutName Retrieves the name of the active input locale identifier. System.Windows.Forms.InputLanguage.LayoutName
GetKeyNameText Retrieves a string that represents the name of a key. System.Windows.Forms.KeyEventArgs.KeyCode.ToString
IsWindowEnabled Determines whether the specified window is enabled for mouse and keyboard input. System.Windows.Forms.Form.Enabled
SetActiveWindow Activates a window. System.Windows.Forms.Activate
SetFocus Sets the keyboard focus to the specified window. System.Windows.Forms.Form.Focus
ToAscii Translates the specified virtual-key code and keyboard state to the corresponding character or characters. System.Windows.Forms.KeyPressEventArgs.KeyChar
ToUnicode Translates the specified virtual-key code and keyboard state to the corresponding Unicode character or characters. System.Windows.Forms.KeyPressEventArgs.KeyChar

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Line and Curve Functions

Win32 function Description .NET Framework API
AngleArc Draws a line segment and an arc. System.Drawing.Graphics.DrawLine
System.Drawing.Graphics.DrawArc
Arc Draws an elliptical arc. System.Drawing.Graphics.DrawArc
ArcTo Draws an elliptical arc. System.Drawing.Graphics.DrawArc
LineTo Draws a line from the current position up to, but not including, the specified point. System.Drawing.Graphics.DrawLine
PolyBezier Draws one or more B&x00E9;zier curves. System.Drawing.Graphics.DrawBeziers
Polyline Draws a series of line segments by connecting the points in the specified array. System.Drawing.Graphics.DrawLines

Alphabetical Win32 Category List
Hierarchical Win32 Category List

List Box Functions

Win32 function Description .NET Framework API
DlgDirList Replaces the contents of a list box with the names of the subdirectories and files in a specified directory. System.Windows.Forms.ListBox.Items.AddRange(System.IO.Directory.GetFileSystemEntries)
DlgDirSelectEx Retrieves the current selection from a single-selection list box. System.Windows.Forms.ListBox.SelectedItem
GetListBoxInfo Retrieves information about the specified list box. System.Windows.Forms.ListBox properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Memory Management Functions

Memory management functions:

Win32 function Description .NET Framework API
GlobalMemoryStatus Obtains information about the system's current usage of both physical and virtual memory. System.Management.ManagementClass("Win32_OperatingSystem")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties
GlobalMemoryStatusEx Obtains information about the system's current usage of both physical and virtual memory. System.Management.ManagementClass("Win32_OperatingSystem")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties

Global and local functions:

Win32 function Description .NET Framework API
GlobalAlloc Allocates the specified number of bytes from the heap. System.Runtime.InteropServices.Marshall.AllocHGlobal
GlobalFree Frees the specified global memory object. System.Runtime.InteropServices.Marshall.FreeHGlobal
GlobalReAlloc Changes the size or attributes of a specified global memory object. System.Runtime.InteropServices.Marshall.ReAllocHGlobal
LocalAlloc Allocates the specified number of bytes from the heap. System.Runtime.InteropServices.Marshall.AllocHGlobal
LocalFree Frees the specified local memory object. System.Runtime.InteropServices.Marshall.FreeHGlobal
LocalReAlloc Changes the size or the attributes of a specified local memory object. System.Runtime.InteropServices.Marshall.ReAllocHGlobal

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Menu Functions

Win32 function Descriptions .NET Framework API
AppendMenu Appends an item to various menus and submenus. System.Windows.Forms.Menu.MenuItemCollection.Add
CheckMenuItem Checks or clears a menu item. System.Windows.Forms.MenuItem.Checked
CheckMenuRadioItem Checks a specified menu item and makes it a radio item. System.Windows.Forms.MenuItem.RadioCheck
CreateMenu Creates a menu. Any of the following:
System.Windows.Forms.ContextMenu constructor
System.Windows.Forms.MainMenu constructor
System.Windows.Forms.Menu.MenuItemCollection constructor
CreatePopupMenu Creates a drop-down menu, submenu, or shortcut menu. Either of the following:
System.Windows.Forms.ContextMenu constructor
System.Windows.Forms.Menu.MenuItemCollection constructor
DeleteMenu Deletes a menu item. System.Windows.Forms.Menu.MenuItemCollection.Remove
DestroyMenu Deletes a menu. System.Windows.Forms.Menu.Dispose
EnableMenuItem Enables, disables, or grays a menu item. System.Windows.Forms.MenuItem.Enabled
GetMenu Gets a handle to the menu. System.Windows.Forms.Form.Menu.Handle
GetMenuBarInfo Gets information about a menu bar. System.Windows.Forms.Form.Menu
GetMenuCheckMarkDimensions Returns the dimensions of the default check-mark bitmap. System.Windows.Forms.SystemInformation.MenuCheckSize
GetMenuDefaultItem Gets the default menu item on a menu. System.Windows.Forms.MenuItem.DefaultItem
GetMenuInfo Gets information about a menu. System.Windows.Forms.MenuItem properties
GetMenuItemCount Gets the number of items in a menu. System.Windows.Forms.Menu.MenuItemCollection.Count
GetMenuItemID Gets the identifier of a menu item. System.Windows.Forms.MenuItem.MenuID
GetMenuItemInfo Gets information about a menu item. System.Windows.Forms.MenuItem properties
GetMenuItemRect Gets the bounding rectangle for a menu item. System.Windows.Forms.MenuItem.DrawItem
System.Windows.Forms.DrawItemEventArgs.Bounds
GetMenuState Gets the menu flags associated with a menu item. System.Windows.Forms.MenuItem.Break
System.Windows.Forms.MenuItem.BarBreak
System.Windows.Forms.MenuItem.Checked
System.Windows.Forms.MenuItem.Enabled
System.Windows.Forms.MenuItem.OwnerDraw
GetMenuString Copies the text string of a menu item into a buffer. System.Windows.Forms.MenuItem.Text
GetSubMenu Gets a handle to the drop-down menu or submenu activated by a menu item. System.Windows.Forms.Menu.MenuItems[].Handle
InsertMenu Inserts a new menu item into a menu. System.Windows.Forms.Menu.MenuItemCollection.Add
InsertMenuItem Inserts a new menu item in a menu. System.Windows.Forms.Menu.MenuItemCollection.Add
ModifyMenu Changes an existing menu item. System.Windows.Forms.MenuItem.Break
System.Windows.Forms.MenuItem.BarBreak
System.Windows.Forms.MenuItem.Checked
System.Windows.Forms.MenuItem.Enabled
System.Windows.Forms.MenuItem.OwnerDraw
System.Windows.Forms.MenuItem.Text
RemoveMenu Deletes a menu item or detaches a submenu from a menu. System.Windows.Forms.Menu.MenuItemCollection.Remove
SetMenu Assigns a new menu to a window. System.Windows.Forms.Form.Menu
SetMenuDefaultItem Sets the default menu item for a menu. System.Windows.Forms.MenuItem.DefaultItem
SetMenuInfo Sets information for a menu. System.Windows.Forms.MenuItem properties
SetMenuItemBitmaps Associates a bitmap with a menu item. System.Windows.Forms.MenuItem.DrawItem
SetMenuItemInfo Changes information about a menu item. System.Windows.Forms.MenuItem properties
TrackPopupMenu Displays a shortcut menu at a location and tracks item selection on a menu. System.Windows.Forms.ContextMenu.Show

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Message and Message Queue Functions

Win32 function Description .NET Framework API
GetMessagePos Retrieves the position of the cursor for the last message retrieved by GetMessage. Inside an event handler:
System.Windows.Forms.Windows.Forms.Control.MousePosition
PostQuitMessage Indicates to the system that a thread has made a request to terminate (quit). System.Windows.Forms.Application.ExitThread
SendMessage Sends the specified message to a window or windows. Any of the following:
System.Windows.Forms.Control.DefWndProc
System.Windows.Forms.Control.WndProc
System.Windows.Forms.Form.DefWndProc
System.Windows.Forms.Form.WndProc

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Metafile Functions

Win32 function Description .NET Framework API
CopyEnhMetaFile Copies the contents of an enhanced-format metafile to a specified file. System.Drawing.Imaging.Metafile.Save
CreateEnhMetaFile Creates a device context for an enhanced-format metafile. System.Drawing.Imaging.Metafile constructor
DeleteEnhMetaFile Deletes an enhanced-format metafile or an enhanced-format metafile handle. System.Drawing.Imaging.Metafile.Dispose
EnhMetaFileProc An application-defined callback function used with EnumEnhMetaFile. System.Drawing.Graphics.EnumerateMetafileProc
EnumEnhMetaFile Enumerates the records within an enhanced-format metafile. System.Drawing.Graphics.EnumerateMetafile
GdiComment Copies a comment from a buffer into a specified enhanced-format metafile. System.Drawing.Graphics.AddMetafileComment
GetEnhMetaFile Creates a handle that identifies the enhanced-format metafile stored in the specified file. System.Drawing.Imaging.Metafile constructor
GetEnhMetaFileBits Retrieves the contents of the specified enhanced-format metafile and copies it into a buffer. System.Drawing.Imaging.Metafile.Save
GetEnhMetaFileHeader Retrieves the record containing the header for the specified enhanced-format metafile. System.Drawing.Imaging.Metafile.GetMetafileHeader
GetEnhMetaFilePaletteEntries Retrieves optional palette entries from the specified enhanced metafile. System.Drawing.Imaging.Metafile.Palette.Entries
GetWinMetaFileBits Converts the enhanced-format records from a metafile into Windows-format records. System.Drawing.Imaging.Metafile.Save
PlayEnhMetaFile Displays the picture stored in the specified enhanced-format metafile. System.Drawing.Graphics.DrawImage
PlayEnhMetaFileRecord Plays an enhanced-metafile record by executing the graphics device interface functions identified by the record. System.Drawing.Imaging.Metafile.PlayRecord
System.Drawing.Imaging.PlayRecordCallback
SetEnhMetaFileBits Creates a memory-based enhanced-format metafile from the specified data. System.Drawing.Imaging.Metafile.Save
SetWinMetaFileBits Converts a metafile from the older Windows format to the new enhanced format. System.Drawing.Imaging.Metafile.Save

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Mouse Input Functions

Win32 function Description .NET Framework API
GetDoubleClickTime Gets the double-click time for the mouse. System.Windows.Forms.SystemInformation.DoubleClickTime
mouse_event Synthesizes mouse motion and button clicks. System.Windows.Forms.MouseEventArgs
ReleaseCapture Releases the mouse capture and restores mouse input processing. System.Windows.Forms.Control.Capture
SetCapture Sets the mouse capture to a window. System.Windows.Forms.Control.Capture
TrackMouseEvent
–or–
_TrackMouseEvent
Posts messages when a mouse leaves a window or hovers over a window. System.Windows.Forms.Control.OnMouseLeave
System.Windows.Forms.Control.OnMouseHover

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Multiple Display Monitor Functions

Win32 function Description .NET Framework API
GetMonitorInfo Retrieves information about a display monitor. System.Windows.Forms.Screen.Bounds
System.Windows.Forms.Screen.Primary
System.Windows.Forms.Screen.WorkingArea
MonitorFromPoint Retrieves a handle to the display monitor that contains a specified point. System.Windows.Forms.Screen.FromPoint
MonitorFromRect Retrieves a handle to the display monitor that has the largest area of intersection with a specified rectangle. System.Windows.Forms.Screen.FromRectangle
MonitorFromWindow Retrieves a handle to the display monitor that has the largest area of intersection with the bounding rectangle of a specified window. System.Windows.Forms.Screen.FromHandle

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Multiple-Document Interface Functions

Win32 function Description .NET Framework API
CreateMDIWindow Creates a multiple-document interface (MDI) child window. System.Windows.Forms.Form constructor
System.Windows.Forms.Form.AutoScroll
System.Windows.Forms.Form.DesktopBounds
System.Windows.Forms.Form.MdiParent
System.Windows.Forms.Form.WindowState
TranslateMDISysAccel Processes accelerator keystrokes for window menu commands of the MDI child windows associated with the specified MDI client window. Keyboard events for MDI children are automatically translated.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

National Language Functions

Win32 function Description .NET Framework API
ConvertDefaultLocale Converts a default locale value to an actual locale identifier. System.Globalization.CultureInfo.CurrentCulture
System.Globalization.CultureInfo.InstalledUICulture
EnumCalendarInfo Enumerates calendar information for a specified locale. Access the System.Globalization.CultureInfo.DateTimeFormat property to get a System.Globalization.DateTimeFormatInfo object, and then access its properties:
System.Globalization.DateTimeFormatInfo.AbbreviatedDayNames
System.Globalization.DateTimeFormatInfo.AbbreviatedMonthNames
System.Globalization.DateTimeFormatInfo.DayNames
System.Globalization.DateTimeFormatInfo.LongDatePattern
System.Globalization.DateTimeFormatInfo.MonthNames
System.Globalization.DateTimeFormatInfo.ShortDatePattern
EnumCalendarInfoEx Enumerates calendar information for a specified locale. Iterate through the calendars:
System.Globalization.CultureInfo.DateTimeFormat.Calendar = System.Globalization.CultureInfo.OptionalCalendars[i]
EnumCalendarInfoProc An application-defined function used with EnumCalendarInfo. Same as EnumCalendarInfo
EnumCalendarInfoProcEx An application-defined function used with EnumCalendarInfoEx. Same as EnumCalendarInfoEx
EnumCodePagesProc An application-defined function used with EnumSystemCodePages. Same as EnumSystemCodePages
EnumDateFormats Enumerates the long or short date formats that are available for a specified locale. System.DateTime.GetDateTimeFormats(System.Globalization.CultureInfo)
EnumDateFormatsEx Enumerates the long or short date formats that are available for a specified locale, including date formats for any alternate calendars. Iterate through the calendars:
System.Globalization.CultureInfo.DateTimeFormat.Calendar = System.Globalization.CultureInfo.OptionalCalendars[i];
System.DateTime.GetDateTimeFormats(System.Globalization.CultureInfo)
EnumDateFormatsProc An application-defined function used with EnumDateFormats. Same as EnumDateFormats
EnumDateFormatsProcEx An application-defined function used with EnumDateFormatsEx. Same as EnumDateFormatsEx
EnumGeoInfoProc A callback function used with EnumSystemGeoID. Same as EnumSystemGeoID
EnumLocalesProc An application-defined function used with EnumSystemLocales. Same as EnumSystemLocales
EnumSystemCodePages Enumerates the code pages that are either installed on or supported by a system. System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures) returns an array of CultureInfo

The various code page properties of System.Globalization.CultureInfo.TextInfo

EnumSystemGeoID Enumerates all GeoIDs on the system. Retrieve an array of CultureInfo by calling System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures), and then access the following CultureInfo properties:
System.Globalization.CultureInfo.ThreeLetterISOLanguageName
System.Globalization.CultureInfo.ThreeLetterWindowsLanguageName
System.Globalization.CultureInfo.TwoLetterISOLanguageName
EnumSystemLocales Enumerates the locales that are either installed on or supported by a system. System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.SpecificCultures)
System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.InstalledWin32Cultures)
EnumTimeFormats Enumerates the time formats that are available for a specified locale. System.DateTime.GetDateTimeFormats
EnumTimeFormatsProc An application-defined function used with EnumTimeFormats. Same as EnumTimeFormats
GetACP Retrieves the current ANSI code-page identifier for the system. System.Globalization.CultureInfo.InstalledUICulture.TextInfo.ANSICodePage
GetCalendarInfo Retrieves information about a calendar. System.Globalization.CultureInfo.DateTimeFormat
GetCurrencyFormat Formats a number string as a currency string for a specified locale. Create a System.Globalization.CultureInfo object using the constructor, specifying either the culture name or identifier (or use the current culture of the application available on System.Threading.Thread.CurrentCulture);
call System.Convert.ToDouble(str) where str is the numeric string you want to format;
and then call System.Double.ToString("C", ci) (or System.Double.ToString("C") to use the current culture), where C is the standard currency format specifier and ci is the CultureInfo object you created

Note    For more information on the variety of formatting options available in the .NET Framework, see System.String.Format.

GetDateFormat Formats a date as a date string for a specified locale. System.DateTime(…, CultureInfo(LCID).Calendar).ToString
GetLocaleInfo Retrieves information about a locale. System.Globalization.CultureInfo.DateTimeFormat
System.Globalization.CultureInfo.NumberFormat
System.Globalization.CultureInfo.TextInfo
GetNumberFormat Formats a number string as a number string customized for a specified locale. Create a System.Globalization.CultureInfo object using the constructor, specifying either the culture name or identifier (or use the current culture of the application available on System.Threading.Thread.CurrentCulture);
call System.Convert.ToDouble(str). where str is the numeric string you want to format;
and then call System.Double.ToString("N", ci) (or System.Double.ToString("N") to use the current culture), where N is the standard number format specifier and ci is the CultureInfo object you created

Note    For more information on the variety of formatting options available in the .NET Framework, see System.String.Format.

GetOEMCP Retrieves the current original equipment manufacturer (OEM) code-page identifier for the system. System.Globalization.CultureInfo.InstalledUICulture.TextInfo.OEMCodePage
GetSystemDefaultLangID Retrieves the language identifier of the system locale. System.Globalization.CultureInfo.InstalledUICulture
GetSystemDefaultLCID Retrieves the system default locale identifier. System.Globalization.CultureInfo.InstalledUICulture
GetSystemDefaultUILanguage Retrieves the language identifier for the default language of the system. System.Globalization.CultureInfo.InstalledUICulture
GetThreadLocale Retrieves the current locale for the calling thread. Either of the following:
System.Globalization.CultureInfo.CurrentCulture
System.Threading.Thread.CurrentCulture
GetTimeFormat Formats time as a time string for a specified locale. System.DateTime(…, CultureInfo(LCID).Calendar).ToString
GetUserDefaultLangID Retrieves the language identifier of the current user locale. System.Globalization.CultureInfo.CurrentCulture
GetUserDefaultLCID Retrieves the user default–locale identifier. System.Globalization.CultureInfo.CurrentCulture
GetUserDefaultUILanguage Retrieves the language identifier for the current user language. System.Globalization.CultureInfo.CurrentUICulture
GetUserGeoID Gets information about the user's location. System.Globalization.RegionInfo
IsValidCodePage Determines whether a specified code page is valid. Use an array of CultureInfo objects returned by:
System.Globalization.CultureInfo.GetCultures(System.Globalization.CultureTypes.AllCultures)

Compare to the code page properties of System.Globalization.CultureInfo.TextInfo

IsValidLocale Determines whether a specified locale identifier is valid. try{ System.Globalization.CultureInfo(LCID) }
LCMapString Maps one character string to another, performing a specified locale-dependent transformation. System.Globalization.SortKey
SetCalendarInfo Sets an item of locale information for a calendar. System.Globalization.CultureInfo.DateTimeFormat
SetLocaleInfo Sets an item of locale information. System.Globalization.CultureInfo.DateTimeFormat
System.Globalization.CultureInfo.NumberFormat
SetThreadLocale Sets the current locale for the calling thread. System.Threading.Thread.CurrentCulture

Note   Sets langid only.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Painting and Drawing Functions

Win32 function Description .NET Framework API
BeginPaint Prepares a window for painting. System.Windows.Forms.Form.OnPaint
DrawFrameControl Draws a frame control. System.Window.Forms.ControlPaint
GetBkColor Returns the background color for a device context. System.Windows.Forms.Form.BackColor
GetBkMode Returns the background mix mode for a device context. System.Windows.Forms.Form.GetStyle(ControlStyles.Opaque)
GetUpdateRect Gets the coordinates of the smallest rectangle that encloses the update region of a window. System.Windows.Forms.PaintEventArgs.ClipRectangle
GetWindowDC Gets the device context for a window, including title bar, menus, and scroll bars. Any of the following:
System.Drawing.Graphics.FromHwnd(Windows.Forms.Control.Handle)
System.Windows.Forms.Control.CreateGraphics.GetHdc
System.Windows.Forms.PaintEventArgs.Graphics.GetHdc
GetWindowRgn Gets a copy of the window region of a window. System.Windows.Forms.Control.Region
GrayString Draws gray text at a location. System.Drawing.Graphics.DrawString(…, Drawing.Brushes.Gray, …)
InvalidateRect Adds a rectangle to the update region of a window. System.Windows.Forms.Control.Invalidate
InvalidateRgn Invalidates the client area within a region. System.Windows.Forms.Control.Invalidate(System.Windows.Forms.Form.ClientRectangle)
RedrawWindow Updates a region in the client area of a window. System.Windows.Forms.Control.Update
SetBkColor Sets the background to a color value. System.Windows.Forms.Form.BackColor
SetBkMode Sets the background mix mode of a device context. System.Windows.Forms.Form.SetStyle(System.Windows.Forms.ControlStyles.Opaque, System.Boolean)
SetWindowRgn Sets the window region of a window. System.Windows.Forms.Control.Region
UpdateWindow Updates the client area of a window. System.Windows.Forms.Control.Update

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Path Functions

Win32 function Description .NET Framework API
CloseFigure Closes an open figure in a path. System.Drawing.Drawing2D.GraphicsPath.CloseFigure
FillPath Closes any open figures in the current path and fills the interior of the path by using the current brush and polygon-filling mode. System.Drawing.Graphics.FillPath
System.Drawing.Drawing2D.GraphicsPath.CloseFigures
FlattenPath Transforms any curves in the path that is selected into the current device context, turning each curve into a sequence of lines. System.Drawing.Drawing2D.GraphicsPath.Flatten
GetMiterLimit Retrieves the miter limit for the specified device context. System.Drawing.Pen.MiterLimit
GetPath Retrieves the coordinates defining the endpoints of lines and the control points of curves found in the path that is selected into the specified device context. System.Drawing.Drawing2D.GraphicsPath.PathData
PathToRegion Creates a region from the path that is selected into the specified device context. System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
SetMiterLimit Sets the limit for the length of miter joins for the specified device context. System.Drawing.Pen.MiterLimit
StrokeAndFillPath Closes any open figures in a path, strokes the outline of the path by using the current pen, and fills its interior by using the current brush. System.Drawing.Graphics.DrawPath
System.Drawing.Graphics.FillPath
System.Drawing.Drawing2D.GraphicsPath.CloseFigures
StrokePath Renders the specified path by using the current pen. System.Drawing.Graphics.DrawPath
WidenPath Redefines the current path as the area that would be painted if the path were stroked using the pen currently selected into the given device context. System.Drawing.Drawing2D.GraphicsPath.Widen

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Pen Functions

Win32 function Description .NET Framework API
CreatePen Creates a logical pen that has the specified style, width, and color. System.Drawing.Pen constructor
ExtCreatePen Creates a logical cosmetic or geometric pen that has the specified style, width, and brush attributes. System.Drawing.Pen constructor

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Performance Monitoring Functions

Win32 function Description .NET Framework API
PdhAddCounter Initializes a counter structure for the specified counter in the specified query. System.Diagnostics.PerformanceCounter constructor
PdhCalculateCounterFromRawValue Computes the current value of a counter using the raw counter data passed in the parameter list. System.Diagnostics.CounterSample.Calculate
PdhCloseLog Closes the specified log file. System.Diagnostics.EventLog.Close
PdhCloseQuery Closes all counters contained in the specified query, closes all handles related to the query, and frees all memory associated with the query. System.Diagnostics.PerformanceCounterCategory.Delete
PdhCollectQueryData Collects the current raw data value for all counters in the specified query and updates the status code of each counter. System.Diagnostics.PerformanceCounterCategory.ReadCategory
PdhEnumObjectItems Returns the available counters and instances provided by the specified object on the specified computer. System.Diagnostics.PerformanceCounterCategory.GetCounters
System.Diagnostics.PerformanceCounterCategory.GetInstanceNames
PdhEnumObjects Returns a list of objects available on the specified computer. System.Diagnostics.PerformanceCounterCategory.GetCategories
PdhFormatFromRawValue Converts one raw performance data value to the specified format or two raw performance data values if the format conversion is time-based. System.Diagnostics.CounterSample.Calculate
PdhGetCounterInfo Retrieves information about a counter, such as data size, counter type, path, and user-supplied data values. System.Diagnostics.PerformanceCounter properties
PdhGetCounterTimeBase Returns the time base of the specified counter. System.Diagnostics.CounterSample.CounterFrequency
PdhGetFormattedCounterValue Returns the current value of a specified counter in the format requested by the caller. System.Diagnostics.PerformanceCounter.NextValue
PdhGetRawCounterArray Returns an array of raw values from the specified counter. System.Diagnostics.PerformanceCounterCategory.ReadCategory
PdhGetRawCounterValue Returns the current raw value of the counter. System.Diagnostics.PerformanceCounter.NextSample

Note   System.Diagnostics.InstanceData holds the raw data.

PdhMakeCounterPath Creates a full counter path using the members specified in the structure passed in the parameter list. All of the following:

System.Diagnostics.PerformanceCounter.MachineName
System.Diagnostics.PerformanceCounter.CategoryName
System.Diagnostics.PerformanceCounter.InstanceName
System.Diagnostics.PerformanceCounter.CounterName

PdhOpenLog Opens the specified log file. System.Diagnotics.EventLog constructor

Note   Must explicitly handle writing to the log file.

PdhOpenQuery Creates and initializes a unique query structure that is used to manage the collection of performance data. System.Diagnostics.PerformanceCounterCategory constructor
PdhValidatePath Validates that the specified counter is present on the computer that is specified in the counter path. Either of the following:
System.Diagnostics.PerformanceCounterCategory.Exists
System.Diagnostics.PerformanceCounterCategory.InstanceExists

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Printing Functions

Functions used to print:

Win32 function Description .NET Framework API
AbortDoc Stops the current print job and erases everything drawn since the last call to StartDoc. System.Drawing.Printing.PrintPageEventArgs.Cancel
DeviceCapabilities Retrieves the capabilities of a printer device driver. System.Drawing.Printing.PrinterSettings.PrinterName
System.Drawing.Printing.PrinterSettings properties
EndDoc Ends a print job. Either of the following:
System.Drawing.Printing.PrintDocument.OnEndPrint
System.Drawing.Printing.PrintController.OnEndPrint
EndPage Notifies the device that the application has finished writing to a page. System.Drawing.Printing.PrintController.OnEndPage
StartDoc Starts a print job. System.Drawing.Printing.PrintDocument.Print
System.Drawing.Printing.PrintDocument.OnBeginPrint
System.Drawing.Printing.PrintController.OnStartPrint
StartPage Prepares the printer driver to accept data. System.Drawing.Printing.PrintDocument.OnQueryPageSettings
System.Drawing.Printing.PrintController.OnStartPage
System.Drawing.Printing.PrintDocument.OnPrintPage

Functions used to access the print spooler:

Win32 function Description .NET Framework API
DocumentProperties Retrieves or modifies printer initialization information or displays a printer-configuration property sheet for the specified printer. System.Windows.Forms.PageSetupDialog
System.Windows.Forms.PrintDialog
EndPagePrinter Notifies the print spooler that the application is at the end of a page in a print job. System.Drawing.Printing.PrintPageEventArgs.HasMorePages
EnumForms Enumerates the forms supported by the specified printer. System.Drawing.Printing.PrinterSettings.PaperSizes
EnumPrinters Enumerates available printers, print servers, domains, or print providers. System.Drawing.Printing.PrinterSettings.InstalledPrinters
GetDefaultPrinter Retrieves the printer name of the default printer for the current user on the local computer. System.Drawing.Printing.PrinterSettings constructor
System.Drawing.Printing.PrinterSettings.PrinterName
GetForm Retrieves information about a specified form. System.Drawing.Printing.PrinterSettings.PaperSizes[]
GetPrinter Retrieves information about a specified printer. System.Drawing.Printing.PrinterSettings.PrinterName
System.Drawing.Printing.PrinterSettings properties
PrinterProperties Displays a printer-properties property sheet for the specified printer. System.Windows.Forms.PageSetupDialog
System.Windows.Forms.PrintDialog
SetPrinter Sets the data for a specified printer or sets the state of the specified printer by pausing printing, resuming printing, or clearing all print jobs. System.Drawing.Printing.PrinterSettings.PrinterName
System.Drawing.Printing.PrinterSettings properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Process and Thread Functions

Functions used with processes:

Win32 function Description .NET Framework API
CreateProcess Creates a new process and its primary thread. System.Diagnostics.Process constructor
System.Diagnostics.Process.Start
ExitProcess Ends a process and all its threads. System.Diagnostics.Process.CloseMainWindow
GetCommandLine Retrieves the command-line string for the current process. Either of the following:
System.Environment.CommandLine
System.Diagnostics.ProcessStartInfo.Arguments
GetCurrentProcess Retrieves a pseudo handle for the current process. System.Diagnostics.Process.Handle
GetCurrentProcessId Retrieves the process identifier of the calling process. System.Diagnostics.Process.Id
GetEnvironmentStrings Retrieves the environment block for the current process. System.Diagnostics.ProcessStartInfo.EnvironmentVariables
GetEnvironmentVariable Retrieves the value of the specified variable from the environment block of the calling process. System.Diagnostics.ProcessStartInfo.EnvironmentVariables[]
GetExitCodeProcess Retrieves the termination status of the specified process. System.Diagnostics.Process.ExitCode
GetPriorityClass Retrieves the priority class for the specified process. System.Diagnostics.Process.PriorityClass
GetProcessAffinityMask Retrieves a process affinity mask for the specified process and the system affinity mask for the system. System.Diagnostics.Process.ProcessorAffinity
GetProcessPriorityBoost Retrieves the priority boost control state of the specified process. System.Diagnostics.Process.PriorityBoostEnabled
GetProcessTimes Retrieves timing information for the specified process. System.Diagnostics.Process.ExitTime
System.Diagnostics.Process.PrivilegedProcessorTime
System.Diagnostics.Process.StartTime
System.Diagnostics.Process.TotalProcessorTime
System.Diagnostics.Process.UserProcessorTime
GetProcessWorkingSetSize Retrieves the minimum and maximum working set sizes of the specified process. System.Diagnostics.Process.MinWorkingSet
System.Diagnostics.Process.MaxWorkingSet
GetStartupInfo Retrieves the contents of the STARTUPINFO structure that was specified when the calling process was created. System.Diagnostics.Process.StandardError
System.Diagnostics.Process.StandardInput
System.Diagnostics.Process.StandardOutput
System.Diagnostics.Process.StartInfo.WindowStyle
OpenProcess Opens an existing process object. System.Diagnostics.Process.GetProcessById
SetEnvironmentVariable Sets the value of an environment variable for the current process. System.Diagnostics.ProcessStartInfo.EnvironmentVariables[]
SetPriorityClass Sets the priority class for the specified process. System.Diagnostics.Process.PriorityClass
SetProcessAffinityMask Sets a processor affinity mask for the threads of a specified process. System.Diagnostics.Process.ProcessorAffinity
SetProcessPriorityBoost Disables the ability of the system to temporarily boost the priority of the threads of the specified process. System.Diagnostics.Process.PriorityBoostEnabled
SetProcessWorkingSetSize Sets the minimum and maximum working set sizes for the specified process. System.Diagnostics.Process.MaxWorkingSet
System.Diagnostics.Process.MinWorkingSet
TerminateProcess Terminates the specified process and all of its threads. System.Diagnostics.Process.Kill

Functions used with threads:

Win32 function Description .NET Framework API
CreateThread Creates a thread to execute within the virtual address space of the calling process. System.Threading.Thread constructor
System.Threading.Thread.Start
GetCurrentThread Retrieves a pseudo handle for the current thread. System.Threading.Thread.CurrentThread
GetCurrentThreadId Retrieves the thread identifier of the calling thread. Either of the following:
System.AppDomain.GetCurrentThreadId
System.Diagnostics.ProcessThread.Id
GetThreadPriority Retrieves the priority value for the specified thread. Either of the following:
System.Diagnostics.ProcessThread.PriorityLevel
System.Threading.Thread.Priority
GetThreadPriorityBoost Retrieves the priority boost control state of the specified thread. System.Diagnostics.ProcessThread.PriorityBoostEnabled
GetThreadTimes Retrieves timing information for the specified thread. System.Diagnostics.ProcessThread.PrivilegedProcessorTime
System.Diagnostics.ProcessThread.StartTime
System.Diagnostics.ProcessThread.TotalProcessorTime
System.Diagnostics.ProcessThread.UserProcessorTime
ResumeThread Decrements the suspend count for a thread. System.Threading.Thread.Resume
SetThreadAffinityMask Sets a processor affinity mask for the specified thread. System.Diagnostics.ProcessThread.ProcessorAffinity
SetThreadIdealProcessor Specifies a preferred processor for a thread. System.Diagnostics.ProcessThread.IdealProcessor
SetThreadPriority Sets the priority value for the specified thread. Either of the following:
System.Diagnostics.ProcessThread.PriorityLevel
System.Threading.Thread.Priority
SetThreadPriorityBoost Enables or disables the ability of the system to temporarily boost the priority of a thread. System.Diagnostics.ProcessThread.PriorityBoostEnabled
Sleep Suspends the execution of the current thread for a specified interval. System.Threading.Thread.Sleep
SuspendThread Suspends the specified thread. System.Threading.Thread.Suspend
SwitchToThread Causes the calling thread to yield execution to another thread that is ready to run on the current processor. System.Threading.Thread.Sleep(0)
TerminateThread Terminates a thread. System.Threading.Thread.Abort
ThreadProc An application-defined function that serves as the starting address for a thread. See System.Threading.ThreadStart delegate
TlsAlloc Allocates a thread local storage (TLS) index. System.Threading.Thread.AllocateNamedDataSlot
TlsFree Releases a TLS index. System.Threading.Thread.FreeNamedDataSlot
TlsGetValue Retrieves the value in the calling thread's TLS slot for a specified TLS index. System.Threading.Thread.GetData
TlsSetValue Stores a value in the calling thread's TLS slot for a specified TLS index. System.Threading.Thread.SetData
WaitForInputIdle Waits until the specified process is waiting for user input with no input pending or until the time-out interval has elapsed. System.Diagnostics.Process.WaitForInputIdle

Functions used in thread pooling:

Win32 function Description .NET Framework API
BindIoCompletionCallback Binds the specified file handle to the I/O completion port for the thread pool. System.Threading.ThreadPool.BindHandle
QueueUserWorkItem Queues a work item to a worker thread in the thread pool. System.Threading.ThreadPool.QueueUserWorkItem
System.Threading.ThreadPool.UnsafeQueueUserWorkItem

Alphabetical Win32 Category List
Hierarchical Win32 Category List

PSAPI Functions

Win32 function Description .NET Framework API
EnumProcesses Retrieves the process identifier for each process object in the system. System.Diagnostics.Process.GetProcesses
EnumProcessModules Retrieves a handle for each module in the specified process. System.Diagnostics.Process.Modules
GetModuleBaseName Retrieves the base name for the specified module. System.Diagnostics.ProcessModule.ModuleName
GetModuleFileNameEx Retrieves the fully qualified path for the specified module. Either of the following:
System.Diagnostics.ProcessModule.FileName
System.Reflection.Module.FullyQualifiedName
GetModuleInformation Retrieves information about the specified module. System.Diagnostics.ProcessModule
GetProcessMemoryInfo Retrieves information about the memory usage of the specified process. System.Diagnostics.Process.PagedMemorySize
System.Diagnostics.Process.PeakPagedMemorySize
System.Diagnostics.Process.PeakWorkingSet
System.Diagnostics.Process.WorkingSet

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Rectangle Functions

Win32 function Description .NET Framework API
EqualRect Determines whether the two specified rectangles are equal by comparing the coordinates of their upper-left and lower-right corners. System.Drawing.Rectangle.Equals
InflateRect Increases or decreases the width and height of the specified rectangle. System.Drawing.Rectangle.Inflate
IntersectRect Calculates the intersection of two source rectangles and places the coordinates of the intersection rectangle into the destination rectangle. System.Drawing.Rectangle.Intersect
IsRectEmpty Determines whether the specified rectangle is empty. System.Drawing.Rectangle.IsEmpty
OffsetRect Moves the specified rectangle by the specified offsets. System.Drawing.Rectangle.Offset
PtInRect Determines whether the specified point lies within the specified rectangle. System.Drawing.Rectangle.Contains
SetRect Sets the coordinates of the specified rectangle. System.Drawing.Rectangle.FromLTRB
SetRectEmpty Creates an empty rectangle in which all coordinates are set to zero. System.Drawing.Rectangle.FromLTRB
UnionRect Creates the union of two rectangles. System.Drawing.Rectangle.Union

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Region Functions

Win32 function Description .NET Framework API
CombineRgn Combines two regions and stores the result in a third region. System.Drawing.Region.Clone
System.Drawing.Region.Exclude
System.Drawing.Region.Intersect
System.Drawing.Region.Union
System.Drawing.Region.Xor
CreateEllipticRgn Creates an elliptical region. System.Drawing.Drawing2D.GraphicsPath constructor
System.Drawing.Drawing2D.GraphicsPath.AddEllipse
System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
CreateEllipticRgnIndirect Creates an elliptical region. System.Drawing.Drawing2D.GraphicsPath constructor
System.Drawing.Drawing2D.GraphicsPath.AddEllipse
System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
CreatePolygonRgn Creates a polygonal region. System.Drawing.Drawing2D.GraphicsPath constructor
System.Drawing.Drawing2D.GraphicsPath.AddPolygon
System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
CreatePolyPolygonRgn Creates a region consisting of a series of polygons. System.Drawing.Drawing2D.GraphicsPath constructor
System.Drawing.Drawing2D.GraphicsPath.AddPolygon
System.Drawing.Region.Region(System.Drawing.Drawing2D.GraphicsPath)
CreateRectRgnIndirect Creates a rectangular region. System.Drawing.Region.Region(System.Drawing.Rectangle)
CreateRoundRectRgn Creates a rectangular region with rounded corners. System.Drawing.Drawing2D.GraphicsPath.AddLines
System.Drawing.Pen.LineJoin = System.Drawing.Drawing2D.LineJoin.Round
EqualRgn Checks the two specified regions to determine whether they are identical. System.Drawing.Region.Equals
ExtCreateRegion Creates a region from the specified region and transformation data. System.Drawing.Region.Transform
FillRgn Fills a region by using the specified brush. System.Drawing.Graphics.FillRegion
GetPolyFillMode Retrieves the current polygon fill mode. System.Drawing.Drawing2D.GraphicsPath.FillMode
GetRegionData Fills the specified buffer with data describing a region. System.Drawing.Region.GetRegionData
GetRgnBox Retrieves the bounding rectangle of the specified region. System.Drawing.Region.GetBounds
OffsetRgn Moves a region by the specified offsets. System.Drawing.Region.Translate
PtInRegion Determines whether the specified point is inside the specified region. System.Drawing.Region.IsVisible
RectInRegion Determines whether any part of the specified rectangle is within the boundaries of a region. System.Drawing.Region.IsVisible
SetPolyFillMode Sets the polygon fill mode for functions that fill polygons. System.Drawing.Drawing2D.GraphicsPath.FillMode

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Registry Functions

Win32 function Description .NET Framework API
RegCloseKey Releases a handle to the specified registry key. Microsoft.Win32.RegistryKey.Close
RegConnectRegistry Establishes a connection to a predefined registry handle on another computer. Microsoft.Win32.RegistryKey.OpenRemoteBaseKey
RegCreateKeyEx Creates the specified registry key. Microsoft.Win32.RegistryKey.CreateSubKey
RegDeleteKey Deletes a subkey. Microsoft.Win32.RegistryKey.DeleteSubKeyTree
RegDeleteValue Removes a named value from the specified registry key. Microsoft.Win32.RegistryKey.DeleteValue
RegEnumKeyEx Enumerates subkeys of the specified open registry key. Microsoft.Win32.RegistryKey.GetSubKeyNames
RegEnumValue Enumerates the values for the specified open registry key. Microsoft.Win32.RegistryKey.GetValueNames
Microsoft.Win32.RegistryKey.GetValue
RegFlushKey Writes all the attributes of the specified open registry key into the registry. Microsoft.Win32.RegistryKey.Flush
RegOpenCurrentUser Retrieves a handle to the HKEY_CURRENT_USER key for the user that the current thread is impersonating. Microsoft.Win32.Registry.CurrentUser
RegOpenKeyEx Opens the specified registry key. Microsoft.Win32.RegistryKey.OpenSubKey
RegOpenUserClassesRoot Retrieves a handle to the HKEY_CLASSES_ROOT key for the specified user. Microsoft.Win32.Registry.ClassesRoot
RegQueryInfoKey Retrieves information about the specified registry key. Microsoft.Win32.RegistryKey.SubKeyCount
Microsoft.Win32.RegistryKey.ValueCount
RegQueryValueEx Retrieves the type and data for a specified value name associated with an open registry key. Microsoft.Win32.RegistryKey.GetValue
RegSetValueEx Sets the data and type of a specified value under a registry key. Microsoft.Win32.RegistryKey.SetValue

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Resource Functions

Win32 function Description .NET Framework API
CopyImage Creates a new icon, cursor, or bitmap and copies the attributes of the old one to the new one. System.Drawing.Image.Clone
EnumResNameProc An application-defined callback function used with EnumResourceNames. System.Resources.ResourceReader.GetEnumerator
EnumResourceNames Searches for resources of a specified type and passes the name or the ID to a callback function. System.Resources.ResourceReader.GetEnumerator
LoadImage Loads an icon, cursor, or bitmap. System.Drawing.Bitmap.Bitmap(System.Type, System.String)
System.Drawing.Icon.Icon(System.Type, System.String)
System.Windows.Forms.Cursor.Cursor(System.Type, System.String)
System.Resources.ResourceManager.GetObject
System.Resources.ResourceSet.GetObject

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Rich Edit Control Functions

Win32 Funtion Description .NET Framework API
EditStreamCallback An application-defined callback function used with the EM_STREAMIN and EM_STREAMOUT messages. System.Windows.Forms.RichTextBox.LoadFile
System.Windows.Forms.RichTextBox.RichTextBox.SaveFile

Note   Not a callback function.

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Scroll Bar Functions

Win32 function Description .NET Framework API
EnableScrollBar Enables or disables one or both scroll bar arrows. System.Windows.Forms.ScrollBar.Enabled

Note   Cannot enable/disable built-in scrollbars (auto-scrolling).

GetScrollBarInfo Retrieves information about the specified scroll bar. System.Windows.Forms.ScrollBar.Value
System.Windows.Forms.ScrollEventArgs.Type
GetScrollInfo Retrieves the parameters of a scroll bar. System.Windows.Forms.ScrollBar.Maximum
System.Windows.Forms.ScrollBar.Minimum
System.Windows.Forms.ScrollBar.Value
GetScrollPos Retrieves the current position of the scroll box. System.Windows.Forms.ScrollBar.Value
GetScrollRange Retrieves the current minimum and maximum scroll box positions. System.Windows.Forms.ScrollBar.Minimum
System.Windows.Forms.ScrollBar.Maximum
SetScrollInfo Sets the parameters of a scroll bar. System.Windows.Forms.ScrollBar.Maximum
System.Windows.Forms.ScrollBar.Minimum
System.Windows.Forms.ScrollBar.Value
SetScrollPos Sets the position of the scroll box. System.Windows.Forms.ScrollBar.Value
SetScrollRange Sets the minimum and maximum scroll box position. System.Windows.Forms.ScrollBar.Minimum
System.Windows.Forms.ScrollBar.Maximum
ShowScrollBar Shows or hides the specified scroll bar. Any of the following:
System.Windows.Forms.Form.AutoScroll
System.Windows.Forms.HScrollBar constructor
System.Windows.Forms.ListBox.HorizontalScrollBar
System.Windows.Forms.ListBox.ScrollAlwaysVisible
System.Windows.Forms.RichTextBox.ScrollBars
System.Windows.Forms.ScrollableControl.HScroll
System.Windows.Forms.ScrollableControl.VScroll
System.Windows.Forms.TextBox.ScrollBars
System.Windows.Forms.VScrollBar constructor

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Service Functions

Functions implemented by services:

Win32 function Description .NET Framework API
Handler An application-defined callback function used with RegisterServiceCtrlHandler. All of the following:
System.ServiceProcess.ServiceBase.OnContinue
System.ServiceProcess.ServiceBase.OnCustomCommand
ServiceProcess.ServiceBase.OnPause
System.ServiceProcess.ServiceBase.OnShutdown
System.ServiceProcess.ServiceBase.OnStop
HandlerEx An application-defined callback function used with RegisterServiceCtrlHandlerEx. All of the following:
System.ServiceProcess.ServiceBase.OnContinue
System.ServiceProcess.ServiceBase.OnCustomCommand
System.ServiceProcess.ServiceBase.OnPause
System.ServiceProcess.ServiceBase.OnPowerEvent
System.ServiceProcess.ServiceBase.OnShutdown
System.ServiceProcess.ServiceBase.OnStop
ServiceMain An application-defined function that serves as the entry point for a service. System.ServiceProcess.ServiceBase.Run

Functions used by programs that control or configure services:

Win32 function Description .NET Framework API
ChangeServiceConfig Changes the configuration parameters of a service. System.ServiceProcess.ServiceController.DisplayName
CloseServiceHandle Closes the specified handle to a service control manager object or a service object. System.ServiceProcess.ServiceController.Close
ControlService Sends a control code to a service. System.ServiceProcess.ServiceController.Continue
System.ServiceProcess.ServiceController.Pause
System.ServiceProcess.ServiceController.Stop
CreateService Creates a service object and adds it to the specified service control manager database. System.ServiceProcess.ServiceBase.ServiceName
System.ServiceProcess.ServiceInstaller.Install
DeleteService Marks the specified service for deletion from the service control manager database. System.ServiceProcess.ServiceInstaller.Uninstall
EnumDependentServices Retrieves the name and status of each service that depends on the specified service. System.ServiceProcess.ServiceController.DependentServices
EnumServicesStatus Enumerates services in the specified service control manager database. System.ServiceProcess.ServiceController.GetServices
GetServiceDisplayName Retrieves the display name of the specified service. System.ServiceProcess.ServiceController.DisplayName
GetServiceKeyName Retrieves the name of the specified service. System.ServiceProcess.ServiceBase.ServiceName
System.ServiceProcess.ServiceController.ServiceName
OpenService Opens an existing service. System.ServiceProcess.ServiceController constructor
QueryServiceConfig Retrieves the configuration parameters of the specified service. System.ServiceProcess.ServiceController.DisplayName
System.ServiceProcess.ServiceController.ServicesDependedOn
System.ServiceProcess.ServiceController.ServiceName
System.ServiceProcess.ServiceController.ServiceType
QueryServiceStatus Retrieves the current status of the specified service. System.ServiceProcess.ServiceController.Status
StartService Starts a service. System.ServiceProcess.ServiceController.Start

Alphabetical Win32 Category List
Hierarchical Win32 Category List

String Functions

Win32 function Description .NET Framework API
CharLower Converts a character string or a single character to lowercase. System.String.ToLower
CharNext Retrieves a pointer to the next character in a string. System.String.GetEnumerator.MoveNext
CharUpper Converts a character string or a single character to uppercase. System.String.ToUpper
CompareString Compares two character strings, using the specified locale. System.String.Compare
IsCharAlpha Determines whether a character is an alphabetical character. System.Char.IsLetter
IsCharAlphaNumeric Determines whether a character is either an alphabetical or a numeric character. System.Char.IsLetterOrDigit
IsCharLower Determines whether a character is lowercase. System.Char.IsLower
IsCharUpper Determines whether a character is uppercase. System.Char.IsUpper
LoadString Loads a string resource from the executable file associated with a specified module. System.Resources.ResourceManager.GetString
lstrcat Appends one string to another. System.String.Concat

Note   Strings are immutable in the .NET Framework. Methods that appear to modify a string actually return a new string.

lstrcmp Compares two character strings. System.String.Compare
lstrcmpi Compares two character strings. System.String.Compare
lstrcpy Copies a string to a buffer. System.String.ToCharArray
lstrcpyn Copies a specified number of characters from a source string into a buffer. System.String.CopyTo
System.String.ToCharArray
lstrlen Retrieves the length of the specified string (not including the terminating null character). System.String.Length
wsprintf Formats and stores a series of characters and values in a buffer. System.String.Format
wvsprintf Formats and stores a series of characters and values in a buffer. System.String.Format

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Structured Exception-Handling Functions

Win32 function Description .NET Framework API
GetExceptionCode Retrieves a code that identifies the type of exception that occurred. System.Exception.GetType
GetExceptionInformation Retrieves a machine-independent description of an exception and information about the machine state that existed for the thread when the exception occurred. System.Exception class
RaiseException Raises an exception in the calling thread. Throw an instance of a System.Exception

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Synchronization Functions

CriticalSection functions:

Win32 function Description .NET Framework API
EnterCriticalSection Waits for ownership of the specified critical section object. System.Threading.Monitor.Enter
LeaveCriticalSection Releases ownership of the specified critical section object. System.Threading.Monitor.Exit
TryEnterCriticalSection Attempts to enter a critical section without blocking. System.Threading.Monitor.TryEnter

Event functions:

Win32 function Description .NET Framework API
CreateEvent Creates or opens a named or an unnamed event object. Either of the following:
System.Threading.AutoResetEvent constructor
System.Threading.ManualResetEvent constructor
ResetEvent Sets the specified event object to the nonsignaled state. Either of the following:
System.Threading.AutoResetEvent.Reset
System.Threading.ManualResetEvent.Reset
SetEvent Sets the specified event object to the signaled state. Either of the following:
System.Threading.AutoResetEvent.Set
System.Threading.ManualResetEvent.Set

Interlocked functions:

Win32 function Description .NET Framework API
InterlockedCompareExchange Performs an atomic comparison of the specified values and exchanges the values, based on the outcome of the comparison. System.Threading.Interlocked.CompareExchange
InterlockedCompareExchangePointer Performs an atomic comparison of the specified values and exchange of the values, based on the outcome of the comparison. System.Threading.Interlocked.CompareExchange
InterlockedDecrement Decrements (decreases by one) the value of the specified variable and checks the resulting value. System.Threading.Interlocked.Decrement
InterlockedExchange Atomically exchanges a pair of values. System.Threading.Interlocked.Exchange
InterlockedIncrement Increments (increases by one) the value of the specified variable and checks the resulting value. System.Threading.Interlocked.Increment

Mutex functions:

Win32 function Description .NET Framework API
CreateMutex Creates or opens a named or an unnamed mutex object. System.Threading.Mutex constructor
OpenMutex Opens an existing named mutex object. System.Threading.Mutex(false, string, name) constructor
ReleaseMutex Releases ownership of the specified mutex object. System.Threading.Mutex.ReleaseMutex

Wait functions:

Win32 function Description .NET Framework API
RegisterWaitForSingleObject Directs a wait thread in the thread pool to wait on the object. System.Threading.ThreadPool.RegisterWaitForSingleObject
System.Threading.ThreadPool.UnsafeRegisterWaitForSingleObject
UnregisterWait Cancels a registered wait operation. System.Threading.RegisteredWaitHandle.Unregister
WaitForMultipleObjects Returns when the specified criteria for the specified objects is met. Either of the following:
System.Threading.WaitHandle.WaitAll
System.Threading.WaitHandle.WaitAny
WaitForSingleObject Returns when the specified criteria for the specified object is met. System.Threading.WaitHandle.WaitOne
WaitOrTimerCallback Returns when the specified criteria is met. See System.Threading.WaitOrTimerCallback delegate

WaitableTimer functions:

Win32 function Description .NET Framework API
CancelWaitableTimer Sets the specified waitable timer to the inactive state. System.Threading.Timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite)
CreateWaitableTimer Creates or opens a waitable timer object. System.Threading.Timer constructor
SetWaitableTimer Activates the specified waitable timer. System.Threading.Timer constructor
TimerAPCProc Application-defined timer completion routine used with SetWaitableTimer. See System.Threading.TimerCallback delegate

Alphabetical Win32 Category List
Hierarchical Win32 Category List

System Information Functions

Win32 function Description .NET Framework API
ExpandEnvironmentStrings Replaces environment-variable strings with their defined values. System.Environment.ExpandEnvironmentVariables
GetComputerName Retrieves the NetBIOS name of the local computer. System.Environment.MachineName
System.Windows.Forms.SystemInformation.ComputerName
GetCurrentHwProfile Retrieves the current hardware profile for the local computer. Use System.Management and Microsoft.Win32.RegistryKey
GetKeyboardType Retrieves information about the current keyboard. System.Management.ManagementClass("Win32_Keyboard")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties
GetNativeSystemInfo Retrieves information about the current system for an application running under WOW64. System.Management.ManagementClass("Win32_Processor")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties
GetSysColor Retrieves the current color of a display element. System.Drawing.SystemColors
GetSystemDirectory Retrieves the path of the system directory. System.Environment.SystemDirectory
GetSystemInfo Retrieves information about the current system. System.Management.ManagementClass("Win32_Processor")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties
GetSystemMetrics Retrieves system metrics and configuration settings. System.Windows.Forms.SystemInformation properties
GetUserName Retrieves the user name of the current thread. System.Environment.UserName
GetVersion Retrieves the version number of the operating system. System.Environment.OSVersion
GetVersionEx Retrieves the version number of the current operating system. System.Environment.OSVersion
GetWindowsDirectory Retrieves the path of the Windows directory. System.Management.ManagementClass("Win32_OperatingSystem")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject["WindowsDirectory"].ToString

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Tape Backup Functions

Win32 function Description .NET Framework API
GetTapeParameters Retrieves information that describes the tape or the tape drive. System.Management.ManagementClass("MSTapeMediaCapacity")
System.Management.ManagementClass("Win32_TapeDrive")
System.Management.ManagementClass.GetInstances
System.Management.ManagementObject.Properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Text Object Model Functions

Win32 function Description .NET Framework API
ITextDocument Retrieves the active selection and range objects for any story in the document. System.Windows.Forms.RichTextBox
ITextFont Encapsulates the functionality of the Microsoft Word Font dialog box. System.Windows.Forms.RichTextBox
ITextPara Encapsulates the functionality of the Microsoft Word Paragraph dialog box. System.Windows.Forms.RichTextBox
ITextRange Enables an application to select text in a story, and then examine or change that text. System.Windows.Forms.RichTextBox

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Time Functions

Win32 function Description .NET Framework API
GetSystemTime Retrieves the current system date and time in UTC format. System.DateTime.UtcNow
GetTimeFormat Formats a system time as a time string for a specified locale. System.DateTime.ToString
SystemTimeToFileTime Converts a system time to a file time. System.DateTime.ToFileTime
FileTimeToLocalFileTime Converts a UTC file time to a local file time. System.DateTime.ToFileTime
GetLocalTime Retrieves the current local date and time. System.DateTime.Now
GetTimeZoneInformation Retrieves the current time-zone parameters. System.TimeZone.CurrentTimeZone
CompareFileTime Compares two file times. System.DateTime.Compare
FileTimeToLocalFileTime Converts a UTC file time to a local file time. System.DateTime.ToLocalTime
FileTimeToSystemTime Converts a file time to system time format. System.DateTime.ToUniversalTime
GetFileTime Retrieves the date and time that a file was created, last accessed, and last modified. Any of the following:
System.IO.Directory.GetCreationTime
System.IO.Directory.GetLastAccessTime
System.IO.Directory.GetLastWriteTime
System.IO.DirectoryInfo.CreationTime
System.IO.DirectoryInfo.LastAccessTime
System.IO.DirectoryInfo.LastWriteTime
System.IO.File.GetCreationTime
System.IO.File.GetLastAccessTime
System.IO.File.GetLastWriteTime
System.IO.FileInfo.CreationTime
System.IO.FileInfo.LastAccessTime
System.IO.FileInfo.LastWriteTime
GetSystemTimeAsFileTime Retrieves the current system date and time in UTC format. System.DateTime.UtcNow.ToFileTimeUtc
LocalFileTimeToFileTime Converts a local file time to a file time based on UTC. System.DateTime.ToFileTimeUtc
SetFileTime Sets the date and time that a file was created, last accessed, or last modified. Any of the following:
System.IO.Directory.SetCreationTime
System.IO.Directory.SetLastAccessTime
System.IO.Directory.SetLastWriteTime
System.IO.DirectoryInfo.CreationTime
System.IO.DirectoryInfo.LastAccessTime
System.IO.DirectoryInfo.LastWriteTime
System.IO.File.SetCreationTime
System.IO.File.SetLastAccessTime
System.IO.File.SetLastWriteTime
System.IO.FileInfo.CreationTime
System.IO.FileInfo.LastAccessTime
System.IO.FileInfo.LastWriteTime
SystemTimeToFileTime Converts a system time to a file time. System.DateTime.ToFileTime
GetTickCount Retrieves the number of milliseconds that have elapsed since the system was started. System.Environment.TickCount

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Timer Functions

Win32 function Description .NET Framework API
KillTimer Destroys the specified timer. System.Threading.Timer.Dispose
System.Timers.Timer.Dispose
System.Windows.Forms.Timer.Dispose
QueryPerformanceCounter Retrieves the current value of the high-resolution performance counter. System.Diagnostics.PerformanceCounter.NextValue
System.Diagnostics.PerformanceCounter.RawValue
QueryPerformanceFrequency Retrieves the frequency of the high-resolution performance counter. System.Diagnostics.PerformanceCounter.CounterType
SetTimer Creates a timer with the specified time-out value. Any of the following:
System.Threading.Timer constructor
System.Timers.Timer constructor
System.Windows.Forms.Timer constructor
System.Windows.Forms.Timer.Interval
TimerProc An application-defined callback function that processes WM_TIMER messages. Either of the following:
System.Threading.TimerCallback delegate
System.Timers.ElapsedEventHandler delegate

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Tool Help Functions

Win32 function Description .NET Framework API
CreateToolhelp32Snapshot Takes a snapshot of the processes and heaps, modules, and threads used by the processes. System.Diagnostics.Process.GetProcesses
System.Diagnostics.Process.Modules
System.Diagnostics.Process.Threads
Module32First Retrieves information about the first module associated with a process. System.Diagnostics.Process.Modules
Module32Next Retrieves information about the next module associated with a process or thread. System.Diagnostics.Process.Modules
Process32First Retrieves information about the first process encountered in a system snapshot. System.Diagnostics.Process.GetProcesses
Process32Next Retrieves information about the next process recorded in a system snapshot. System.Diagnostics.Process.GetProcesses
Thread32First Retrieves information about the first thread of any process encountered in a system snapshot. System.Diagnostics.Process.Threads
Thread32Next Retrieves information about the next thread of any process encountered in the system memory snapshot. System.Diagnostics.Process.Threads

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Unicode and Character Set Functions

Win32 function Description .NET Framework API
GetTextCharset Retrieves a character-set identifier for the font that is currently selected into a specified device context. System.Drawing.Font.GdiCharSet

Alphabetical Win32 Category List
Hierarchical Win32 Category List

User Profile Functions

Win32 function Description .NET Framework API
CreateEnvironmentBlock Retrieves the environment variables for the specified user. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue
DeleteProfile Deletes the user profile and all user-related settings from the specified computer. System.IO.Directory.Delete
Microsoft.Win32.Registry
Microsoft.Win32.RegistryKey.DeleteSubKey
ExpandEnvironmentStringsForUser Expands the source string by using the environment block established for the specified user. Microsoft.Win32.Registry class

Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValueNames, and then call GetValue for each name

GetAllUsersProfileDirectory Retrieves the path to the root of the All Users profile. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue
GetDefaultUserProfileDirectory Retrieves the path to the root of the Default User profile. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue
GetProfilesDirectory Retrieves the path to the root directory where all of the user profiles are stored. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue
GetUserProfileDirectory Retrieves the path to the root directory of the profile for the specified user. Microsoft.Win32.Registry class
Microsoft.Win32.RegistryKey.OpenSubKey(name).GetValue

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Version Information Functions

Win32 function Description .NET Framework API
GetFileVersionInfo Retrieves version information for the specified file. System.Diagnostics.FileVersionInfo.GetVersionInfo
GetFileVersionInfoSize Determines whether the operating system can retrieve version information for a specified file. If version information is available, the function returns the size, in bytes, of that information. System.Diagnostics.FileVersionInfo.GetVersionInfo
VerLanguageName Retrieves a description string for the language associated with a specified binary Microsoft language identifier. System.Globalization.CultureInfo.Name
VerQueryValue Retrieves specified version information from the specified version-information resource. System.Diagnostics.FileVersionInfo properties

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Window Functions

Win32 function Description .NET Framework API
AdjustWindowRect Calculates the required size of the window rectangle, based on the desired client-rectangle size. System.Windows.Forms.Form.ClientSize
AdjustWindowRectEx Calculates the required size of the window rectangle, based on the desired client-rectangle size. System.Windows.Forms.Form.ClientSize
ArrangeIconicWindows Arranges all minimized (iconic) child windows of the specified parent window. System.Windows.Forms.Form.LayoutMdi(MdiLayout.ArrangeIcons)
BringWindowToTop Brings the specified window to the top of the Z order. System.Windows.Forms.Form.BringToFront
CascadeWindows Cascades the specified child windows of the specified parent window. System.Windows.Forms.Form.LayoutMdi(MdiLayout.Cascade)
ChildWindowFromPoint Determines which, if any, of the child windows belonging to a parent window contains the specified point. System.Windows.Forms.Form.GetChildAtPoint
CloseWindow Minimizes (but does not destroy) the specified window. System.Windows.Forms.Form.WindowState = System.Windows.Forms.FormWindowState.Minimized
CreateWindow Creates an overlapped, pop-up, or child window. System.Windows.Forms.Form constructor
CreateWindowEx Creates an overlapped, pop-up, or child window with an extended window style. System.Windows.Forms.Form constructor
DestroyWindow Destroys the specified window. System.Windows.Forms.Form.Close
EnumChildProc An application-defined callback function used with EnumChildWindows. Same as EnumChildWindows
EnumChildWindows Enumerates the child windows that belong to the specified parent window. System.Windows.Forms.Form.Controls
GetAncestor Retrieves the handle to the ancestor of the specified window. System.Windows.Forms.Form.FindForm
System.Windows.Forms.Form.Owner
System.Windows.Forms.Form.Parent
GetClientRect Retrieves the coordinates of the client area for a window. System.Windows.Forms.Form.ClientRectangle
GetForegroundWindow Returns a handle to the foreground window. System.Windows.Forms.Form.ActiveForm
GetLayeredWindowAttributes Retrieves the opacity and transparency color key of a layered window. System.Windows.Forms.Form.Opacity
System.Windows.Forms.Form.TransparencyKey
GetNextWindow Retrieves a handle to the next or previous window in Z order. System.Windows.Forms.Form.Controls[1 +/- Control.IndexOf]
GetParent Retrieves a handle to the parent window for the specified child window. System.Windows.Forms.Form.FindForm
System.Windows.Forms.Form.Parent
GetTitleBarInfo Retrieves information about the specified title bar. System.Windows.Forms.Form.SystemInformation.CaptionButtonSize
System.Windows.Forms.Form.SystemInformation.CaptionHeight
System.Windows.Forms.Form.HelpButton
System.Windows.Forms.Form.MaximizeBox
System.Windows.Forms.Form.MinimizeBox
GetTopWindow Retrieves a handle to the child window at the top of the Z order. System.Windows.Forms.Form.Controls[0]
GetWindow Retrieves a handle to a window that has the specified relationship to the specified window. System.Windows.Forms.Form.Controls
GetWindowInfo Retrieves information about the specified window. System.Windows.Forms.Form.ClientSize
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form.Name
System.Windows.Forms.Form.ProductVersion
System.Windows.Forms.Form.Size
System.Windows.Forms.SystemInformation.BorderSize
GetWindowPlacement Retrieves the show state and the restored, minimized, and maximized positions of the specified window. System.Windows.Forms.Form.Bounds
System.Windows.Forms.Form.MaximizedBounds
System.Windows.Forms.Form.Visible
System.Windows.Forms.Form.WindowState
GetWindowRect Retrieves the dimensions of the bounding rectangle of the specified window. System.Windows.Forms.Form.Bounds
GetWindowText Copies the text of the title bar of the specified window. System.Windows.Forms.Form.Text
GetWindowTextLength Retrieves the length of the title bar text for the specified window. System.Windows.Forms.Form.Text.Length
IsChild Tests whether a window is a child window or descendant window of a specified parent window. System.Windows.Forms.Form.Contains
System.Windows.Forms.Form.IsMdiChild
IsIconic Determines whether the specified window is minimized (iconic). System.Windows.Forms.Form.WindowState
IsWindowVisible Retrieves the visibility state of the specified window. System.Windows.Forms.Form.Visible
IsZoomed Determines whether a window is maximized (zoomed). System.Windows.Forms.Form.WindowState
MoveWindow Changes the position and dimensions of the specified window. System.Windows.Forms.Form.SetBounds
OpenIcon Restores a minimized (iconic) window to its previous size and position. System.Windows.Forms.Form.WindowState = System.Windows.Forms.FormWindowState.Normal
SetForegroundWindow Puts the thread that created the specified window into the foreground and activates the window. System.Windows.Forms.Form.Activate
SetLayeredWindowAttributes Sets the opacity and transparency color key of a layered window. System.Windows.Forms.Form.Opacity
System.Windows.Forms.Form.TransparencyKey
SetParent Changes the parent window of the specified child window. System.Windows.Forms.Form.Parent
SetWindowPlacement Sets the show state and the restored, minimized, and maximized positions of the specified window. System.Windows.Forms.Form.Bounds
System.Windows.Forms.Form.MaximizedBounds
System.Windows.Forms.Form.SetBounds
System.Windows.Forms.Form.Visible
System.Windows.Forms.Form.WindowState
SetWindowPos Changes the size, position, and Z order of a window. System.Windows.Forms.Form.BringToFront
System.Windows.Forms.Form.Enabled
System.Windows.Forms.Form.SendToBack
System.Windows.Forms.Form.SetBounds
System.Windows.Forms.Form.TopMost
System.Windows.Forms.Form.Visible
SetWindowText Changes the text of the title bar for the specified window. System.Windows.Forms.Form.Text
ShowWindow Sets the show state of the specified window. System.Windows.Forms.Form.Show
System.Windows.Forms.Form.Visible
System.Windows.Forms.Form.WindowState
TileWindows Tiles the specified child windows of the specified parent window. System.Windows.Forms.Form.LayoutMdi(MdiLayout.TileHorizontal)
System.Windows.Forms.Form.LayoutMdi(MdiLayout.TileVertical)
WindowFromPoint Retrieves a handle to the window that contains the specified point. System.Windows.Forms.Form.GetChildAtPoint

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Window Class Functions

Win32 function Description .NET Framework API
GetClassInfo Retrieves information about a window class. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
GetClassLong Retrieves the specified 32-bit value from the WNDCLASSEX structure associated with the specified window. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
GetClassLongPtr Retrieves the specified value from the WNDCLASSEX structure associated with the specified window. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
GetClassName Retrieves the name of the class to which the specified window belongs. System.Windows.Forms.Control.Name
GetWindowLong Retrieves information about the specified window. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Parent
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form properties
GetWindowLongPtr Retrieves information about the specified window. System.ComponentModel.Component.Events
System.Windows.Forms.Control.Parent
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form properties
RegisterClass Registers a window class. System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
System.Windows.Forms.Form events
SetClassLong Replaces the specified 32-bit value at the specified offset into the extra class memory or the WNDCLASSEX structure. System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
System.Windows.Forms.Form events
SetClassLongPtr Replaces the specified value at the specified offset into the extra class memory or the WNDCLASSEX structure. System.Windows.Forms.Control.Cursor
System.Windows.Forms.Control.Name
System.Windows.Forms.Form.BackColor
System.Windows.Forms.Form.Icon
System.Windows.Forms.Form.Menu
System.Windows.Forms.Form.CreateParams.ClassStyle
System.Windows.Forms.Form events
SetWindowLong Changes an attribute of the specified window. System.Windows.Forms.Control.Parent
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form properties
System.Windows.Forms.Form events
SetWindowLongPtr Changes an attribute of the specified window. System.Windows.Forms.Control.Parent
System.Windows.Forms.Form.CreateParams.ExStyle
System.Windows.Forms.Form.CreateParams.Style
System.Windows.Forms.Form properties
System.Windows.Forms.Form events

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Window Procedure Functions

Win32 function Description .NET Framework API
DefWindowProc Calls the default window procedure to provide default processing for any window messages that an application does not process. Any of the following:
System.Windows.Forms.Form.DefWndProc
System.Windows.Forms.Control.DefWndProc
System.Windows.Forms.NativeWindow.DefWndProc
WindowProc An application-defined function that processes messages sent to a window. Any of the following:
System.Windows.Forms.Form.WndProc
System.Windows.Forms.Control.WndProc
System.Windows.Forms.NativeWindow.WndProc

Alphabetical Win32 Category List
Hierarchical Win32 Category List

Window Property Functions

Win32 function Description .NET Framework API
GetProp Retrieves a data handle from the property list of the specified window. System.Windows.Forms.Control.Tag
RemoveProp Removes an entry from the property list of the specified window. System.Windows.Forms.Control.Tag
SetProp Adds a new entry or changes an existing entry in the property list of the specified window.
发表在 article | 标签为 | 59条评论

linux指令大全(完整篇)

cat cd
chmod chown
cp cut

名称:cat
使用权限:所有使用者
使用方式:cat [-AbeEnstTuv] [--help] [--version] fileName
说明:把档案串连接后传到基本输出(萤幕或加 > fileName 到另一个档案)
参数:
-n 或 --number 由 1 开始对所有输出的行数编号
-b 或 --number-nonblank 和 -n 相似,只不过对于空白行不编号
-s 或 --squeeze-blank 当遇到有连续两行以上的空白行,就代换为一行的空白行
-v 或 --show-nonprinting

范例:
cat -n textfile1 > textfile2 把 textfile1 的档案内容加上行号后输入 textfile2 这个档案里
cat -b textfile1 textfile2 >> textfile3 把 textfile1 和 textfile2 的档案内容加上行号(空白行不加)之后将内容附加到 textfile3

名称 : cd
使用权限 : 所有使用者

使用方式 : cd [dirName]

说明 : 变换工作目录至 dirName。 其中 dirName 表示法可为绝对路径或相对路径。若目录名称省略,则变换至使用者的 home directory (也就是刚 login 时所在的目录)。

另外,"~" 也表示为 home directory 的意思,"." 则是表示目前所在的目录,".." 则表示目前目录位置的上一层目录。

范例 : 跳到 /usr/bin/ :
cd /usr/bin

跳到自己的 home directory :
cd ~

跳到目前目录的上上两层 :
cd ../..

指令名称 : chmod
使用权限 : 所有使用者

使用方式 : chmod [-cfvR] [--help] [--version] mode file...

说明 : Linux/Unix 的档案存取权限分为三级 : 档案拥有者、群组、其他。利用 chmod 可以藉以控制档案如何被他人所存取。

把计 :

mode : 权限设定字串,格式如下 : [ugoa...][[+-=][rwxX]...][,...],其中u 表示该档案的拥有者,g 表示与该档案的拥有者属于同一个群体(group)者,o 表示其他以外的人,a 表示这三者皆是。
+ 表示增加权限、- 表示取消权限、= 表示唯一设定权限。
r 表示可读取,w 表示可写入,x 表示可执行,X 表示只有当该档案是个子目录或者该档案已经被设定过为可执行。
-c : 若该档案权限确实已经更改,才显示其更改动作
-f : 若该档案权限无法被更改也不要显示错误讯息
-v : 显示权限变更的详细资料
-R : 对目前目录下的所有档案与子目录进行相同的权限变更(即以递回的方式逐个变更)
--help : 显示辅助说明
--version : 显示版本

范例 :将档案 file1.txt 设为所有人皆可读取 :
chmod ugo+r file1.txt

将档案 file1.txt 设为所有人皆可读取 :
chmod a+r file1.txt

将档案 file1.txt 与 file2.txt 设为该档案拥有者,与其所属同一个群体者可写入,但其他以外的人则不可写入 :
chmod ug+w,o-w file1.txt file2.txt

将 ex1.py 设定为只有该档案拥有者可以执行 :
chmod u+x ex1.py

将目前目录下的所有档案与子目录皆设为任何人可读取 :
chmod -R a+r *

此外chmod也可以用数字来表示权限如 chmod 777 file
语法为:chmod abc file

其中a,b,c各为一个数字,分别表示User、Group、及Other的权限。

r=4,w=2,x=1
若要rwx属性则4+2+1=7;
若要rw-属性则4+2=6;
若要r-x属性则4+1=7。

范例:
chmod a=rwx file


chmod 777 file

效果相同
chmod ug=rwx,o=x file


chmod 771 file

效果相同

若用chmod 4755 filename可使此程式具有root的权限

指令名称 : chown
使用权限 : root

使用方式 : chmod [-cfhvR] [--help] [--version] user[:group] file...

说明 : Linux/Unix 是多人多工作业系统,所有的档案皆有拥有者。利用 chown 可以将档案的拥有者加以改变。一般来说,这个指令只有是由系统管理者(root)所使用,一般使用者没有权限可以改变别人的档案拥有者,也没有权限可以自己的档案拥有者改设为别人。只有系统管理者(root)才有这样的权限。

把计 :

user : 新的档案拥有者的使用者 IDgroup : 新的档案拥有者的使用者群体(group)-c : 若该档案拥有者确实已经更改,才显示其更改动作-f : 若该档案拥有者无法被更改也不要显示错误讯息-h : 只对于连结(link)进行变更,而非该 link 真正指向的档案-v : 显示拥有者变更的详细资料-R : 对目前目录下的所有档案与子目录进行相同的拥有者变更(即以递回的方式逐个变更)--help : 显示辅助说明--version : 显示版本

范例 :
将档案 file1.txt 的拥有者设为 users 群体的使用者 jessie :
chown jessie:users file1.txt

将目前目录下的所有档案与子目录的拥有者皆设为 users 群体的使用者 lamport :
chmod -R lamport:users *

名称:cp
使用权限:所有使用者

使用方式:

cp [options] source dest
cp [options] source... directory

说明:将一个档案拷贝至另一档案,或将数个档案拷贝至另一目录。

把计

-a 尽可能将档案状态、权限等资料都照原状予以复制。
-r 若 source 中含有目录名,则将目录下之档案亦皆依序拷贝至目的地。
-f 若目的地已经有相同档名的档案存在,则在复制前先予以删除再行复制。
范例:
将档案 aaa 复制(已存在),并命名为 bbb :
cp aaa bbb

将所有的C语言程式拷贝至 Finished 子目录中 :
cp *.c Finished

名称:cut

使用权限:所有使用者

用法:cut -cnum1-num2 filename

说明:显示每行从开头算起 num1 到 num2 的文字。

范例:

shell>> cat example
test2
this is test1
shell>> cut -c0-6 example ## print 开头算起前 6 个字元
test2
this i

名称 : find
用法 : find
使用说明 :

将档案系统内符合 expression 的档案列出来。你可以指要档案的名称、类别、时间、大小、权限等不同资讯的组合,只有完全相符的才会被列出来。

find 根据下列规则判断 path 和 expression,在命令列上第一个 - ( ) , ! 之前的部份为 path,之后的是 expression。如果 path 是空字串则使用目前路径,如果 expression 是空字串则使用 -print 为预设 expression

expression 中可使用的选项有二三十个之多,在此只介绍最常用的部份。

-mount, -xdev : 只检查和指定目录在同一个档案系统下的档案,避免列出其它档案系统中的档案
-amin n : 在过去 n 分钟内被读取过
-anewer file : 比档案 file 更晚被读取过的档案
-atime n : 在过去 n 天过读取过的档案
-cmin n : 在过去 n 分钟内被修改过
-cnewer file :比档案 file 更新的档案
-ctime n : 在过去 n 天过修改过的档案
-empty : 空的档案-gid n or -group name : gid 是 n 或是 group 名称是 name
-ipath p, -path p : 路径名称符合 p 的档案,ipath 会忽略大小写
-name name, -iname name : 档案名称符合 name 的档案。iname 会忽略大小写
-size n : 档案大小 是 n 单位,b 代表 512 位元组的区块,c 表示字元数,k 表示 kilo bytes,w 是二个位元组。-type c : 档案类型是 c 的档案。
d: 目录
c: 字型装置档案
b: 区块装置档案
p: 具名贮列
f: 一般档案
l: 符号连结
s: socket
-pid n : process id 是 n 的档案

你可以使用 ( ) 将运算式分隔,并使用下列运算。
exp1 -and exp2
! expr
-not expr
exp1 -or exp2
exp1, exp2
范例:
将目前目录及其子目录下所有延伸档名是 c 的档案列出来。
# find . -name "*.c"

将目前目录其其下子目录中所有一般档案列出
# find . -ftype f

将目前目录及其子目录下所有最近 20 分钟内更新过的档案列出
# find . -ctime -20

名称:less

使用权限:所有使用者

使用方式:

less [Option] filename

说明:
less 的作用与 more 十分相似,都可以用来浏览文字档案的内容,不同的是 less 允许使用者往回卷动
以浏览已经看过的部份,同时因为 less 并未在一开始就读入整个档案,因此在遇上大型档案的开启时,会比一般的文书编辑器(如 vi)来的快速。

范例:

指令名称 : ln
使用权限 : 所有使用者

使用方式 : ln [options] source dist,其中 option 的格式为 :

[-bdfinsvF] [-S backup-suffix] [-V {numbered,existing,simple}]
[--help] [--version] [--]
说明 : Linux/Unix 档案系统中,有所谓的连结(link),我们可以将其视为档案的别名,而连结又可分为两种 : 硬连结(hard link)与软连结(symbolic link),硬连结的意思是一个档案可以有多个名称,而软连结的方式则是产生一个特殊的档案,该档案的内容是指向另一个档案的位置。硬连结是存在同一个档案系统中,而软连结却可以跨越不同的档案系统。
ln source dist 是产生一个连结(dist)到 source,至于使用硬连结或软链结则由参数决定。

不论是硬连结或软链结都不会将原本的档案复制一份,只会占用非常少量的磁碟空间。

-f : 链结时先将与 dist 同档名的档案删除-d : 允许系统管理者硬链结自己的目录-i : 在删除与 dist 同档名的档案时先进行询问-n : 在进行软连结时,将 dist 视为一般的档案-s : 进行软链结(symbolic link)-v : 在连结之前显示其档名-b : 将在链结时会被覆写或删除的档案进行备份-S SUFFIX : 将备份的档案都加上 SUFFIX 的字尾-V METHOD : 指定备份的方式--help : 显示辅助说明--version : 显示版本
范例 :
将档案 yy 产生一个 symbolic link : zz
ln -s yy zz

将档案 yy 产生一个 hard link : zz
ln yy xx

名称:locate
使用权限:所有使用者
使用方式: locate [-q] [-d ] [--database=]
locate [-r ] [--regexp=]
locate [-qv] [-o ] [--output=]
locate [-e ] [-f ] <[-l ] [-c]
<[-U ] [-u]>
locate [-Vh] [--version] [--help]
说明:
locate 让使用者可以很快速的搜寻档案系统内是否有指定的档案。其方法是先建立一个包括系统内所有档案名称及路径的资料库,之后当寻找时就只需查询这个资料库,而不必实际深入档案系统之中了。

在一般的 distribution 之中,资料库的建立都被放在 contab 中自动执行。一般使用者在使用时只要用

# locate your_file_name

的型式就可以了。 参数:
-u
-U

建立资料库,-u 会由根目录开始,-U 则可以指定开始的位置。

-e


排除在寻找的范围之外。

-l
如果 是 1.则启动安全模式。在安全模式下,使用者不会看到权限无法看到的档案。这会始速度减慢,因为 locate 必须至实际的档案系统中取得档案的权限资料。

-f
将特定的档案系统排除在外,例如我们没有到理要把 proc 档案系统中的档案放在资料库中。

-q
安静模式,不会显示任何错误讯息。

-n
至多显示 个输出。

-r
使用正规运算式 做寻找的条件。

-o
指定资料库存的名称。

-d

指定资料库的路径

-h
显示辅助讯息

-v
显示更多的讯息

-V
显示程式的版本讯息 范例:

locate chdrv : 寻找所有叫 chdrv 的档案
locate -n 100 a.out : 寻找所有叫 a.out 的档案,但最多只显示 100 个
locate -u : 建立资料库

名称 : ls
使用权限 : 所有使用者

使用方式 : ls [-alrtAFR] [name...]

说明 : 显示指定工作目录下之内容(列出目前工作目录所含之档案及子目录)。-a 显示所有档案及目录 (ls内定将档案名或目录名称开头为"."的视为隐藏档,不会列出)
-l 除档案名称外,亦将档案型态、权限、拥有者、档案大小等资讯详细列出
-r 将档案以相反次序显示(原定依英文字母次序)
-t 将档案依建立时间之先后次序列出
-A 同 -a ,但不列出 "." (目前目录) 及 ".." (父目录)
-F 在列出的档案名称后加一符号;例如可执行档则加 "*", 目录则加 "/"
-R 若目录下有档案,则以下之档案亦皆依序列出

范例:
列出目前工作目录下所有名称是 s 开头的档案,愈新的排愈后面 :
ls -ltr s*

将 /bin 目录以下所有目录及档案详细资料列出 :
ls -lR /bin

列出目前工作目录下所有档案及目录;目录于名称后加 "/", 可执行档于名称后加 "*" :
ls -AF

名称:more
使用权限:所有使用者
使用方式:more [-dlfpcsu] [-num] [+/pattern] [+linenum] [fileNames..]
说明:类似 cat ,不过会以一页一页的显示方便使用者逐页阅读,而最基本的指令就是按空白键(space)就往下一页显示,按 b 键就会往回(back)一页显示,而且还有搜寻字串的功能(与 vi 相似),使用中的说明文件,请按 h 。
参数:-num 一次显示的行数
-d 提示使用者,在画面下方显示 [Press space to continue, q to quit.] ,如果使用者按错键,则会显示 [Press h for instructions.] 而不是 哔 声
-l 取消遇见特殊字元 ^L(送纸字元)时会暂停的功能
-f 计算行数时,以实际上的行数,而非自动换行过后的行数(有些单行字数太长的会被扩展为两行或两行以上)
-p 不以卷动的方式显示每一页,而是先清除萤幕后再显示内容
-c 跟 -p 相似,不同的是先显示内容再清除其他旧资料
-s 当遇到有连续两行以上的空白行,就代换为一行的空白行
-u 不显示下引号 (根据环境变数 TERM 指定的 terminal 而有所不同)
+/ 在每个档案显示前搜寻该字串(pattern),然后从该字串之后开始显示
+num 从第 num 行开始显示
fileNames 欲显示内容的档案,可为复数个数
范例:
more -s testfile 逐页显示 testfile 之档案内容,如有连续两行以上空白行则以一行空白行显示。
more +20 testfile 从第 20 行开始显示 testfile 之档案内容。

名称:mv
使用权限:所有使用者

使用方式:

mv [options] source dest
mv [options] source... directory
说明:将一个档案移至另一档案,或将数个档案移至另一目录。
参数:-i 若目的地已有同名档案,则先询问是否覆盖旧档。

范例:

将档案 aaa 更名为 bbb :
mv aaa bbb

将所有的C语言程式移至 Finished 子目录中 :
mv -i *.c

名称:rm
使用权限:所有使用者

使用方式:rm [options] name...

说明:删除档案及目录。

把计

-i 删除前逐一询问确认。
-f 即使原档案属性设为唯读,亦直接删除,无需逐一确认。
-r 将目录及以下之档案亦逐一删除。
范例:
删除所有C语言程式档;删除前逐一询问确认 :
rm -i *.c

将 Finished 子目录及子目录中所有档案删除 :
rm -r Finished

名称:rmdir
使用权限:于目前目录有适当权限的所有使用者

使用方式: rmdir [-p] dirName

说明: 删除空的目录。

参数: -p 是当子目录被删除后使它也成为空目录的话,则顺便一并删除。

范例:

将工作目录下,名为 AAA 的子目录删除 :
rmdir AAA

在工作目录下的 BBB 目录中,删除名为 Test 的子目录。若 Test 删除后,BBB 目录成为空目录,则 BBB 亦予删除。
rmdir -p BBB/Test

名称:split
使用权限:所有使用者

使用方式:split [OPTION] [INPUT [PREFIX]]

说明:

将一个档案分割成数个。而从 INPUT 分割输出成固定大小的档案,其档名依序为 PREFIXaa, PREFIXab...;PREFIX 预设值为 `x。若没有 INPUT 档或为 `-,则从标准输入读进资料。

匡兜

-b, --bytes=SIZE

SIZE 值为每一输出档案的大小,单位为 byte。
-C, --line-bytes=SIZE

每一输出档中,单行的最大 byte 数。
-l, --lines=NUMBER

NUMBER 值为每一输出档的列数大小。
-NUMBER

与 -l NUMBER 相同。
--verbose

于每个输出档被开启前,列印出侦错资讯到标准错误输出。
--help

显示辅助资讯然后离开。
--version

列出版本资讯然后离开。
SIZE 可加入单位: b 代表 512, k 代表 1K, m 代表 1 Meg。

范例:

PostgresSQL 大型资料库备份与回存:

因 Postgres 允许表格大过你系统档案的最大容量,所以要将表格 dump 到单一的档案可能会有问题,使用 split进行档案分割。

% pg_dump dbname | split -b 1m - filename.dump.

重新载入

% createdb dbname
% cat filename.dump.* | pgsql dbname

名称:touch
使用权限:所有使用者

使用方式:
touch [-acfm]
[-r reference-file] [--file=reference-file]
[-t MMDDhhmm[[CC]YY][.ss]]
[-d time] [--date=time] [--time={atime,access,use,mtime,modify}]
[--no-create] [--help] [--version]
file1 [file2 ...]

说明:
touch 指令改变档案的时间记录。 ls -l 可以显示档案的时间记录。

参数:
a 改变档案的读取时间记录。
m 改变档案的修改时间记录。
c 假如目的档案不存在,不会建立新的档案。与 --no-create 的效果一样。
f 不使用,是为了与其他 unix 系统的相容性而保留。
r 使用参考档的时间记录,与 --file 的效果一样。
d 设定时间与日期,可以使用各种不同的格式。
t 设定档案的时间记录,格式与 date 指令相同。
--no-create 不会建立新档案。
--help 列出指令格式。
--version 列出版本讯息。

范例:

最简单的使用方式,将档案的时候记录改为现在的时间。若档案不存在,系统会建立一个新的档案。

touch file
touch file1 file2

将 file 的时间记录改为 5 月 6 日 18 点 3 分,公元两千年。时间的格式可以参考 date 指令,至少需输入 MMDDHHmm ,就是月日时与分。

touch -c -t 05061803 file
touch -c -t 050618032000 file

将 file 的时间记录改变成与 referencefile 一样。

touch -r referencefile file

将 file 的时间记录改成 5 月 6 日 18 点 3 分,公元两千年。时间可以使用 am, pm 或是 24 小时的格式,日期可以使用其他格式如 6 May 2000 。

touch -d "6:03pm" file
touch -d "05/06/2000" file
touch -d "6:03pm 05/06/2000" file
名称 : at
使用权限 : 所有使用者

使用方式 : at -V [-q queue] [-f file] [-mldbv] TIME

说明 : at 可以让使用者指定在 TIME 这个特定时刻执行某个程式或指令,TIME 的格式是 HH:MM其中的 HH 为小时,MM 为分钟,甚至你也可以指定 am, pm, midnight, noon, teatime(就是下午 4 点锺)等口语词。

如果想要指定超过一天内的时间,则可以用 MMDDYY 或者 MM/DD/YY 的格式,其中 MM 是分钟,DD 是第几日,YY 是指年份。另外,使用者甚至也可以使用像是 now + 时间间隔来弹性指定时间,其中的时间间隔可以是 minutes, hours, days, weeks

另外,使用者也可指定 today 或 tomorrow 来表示今天或明天。当指定了时间并按下 enter 之后,at 会进入交谈模式并要求输入指令或程式,当你输入完后按下 ctrl+D 即可完成所有动作,至于执行的结果将会寄回你的帐号中。

把计 :

-V : 印出版本编号
-q : 使用指定的伫列(Queue)来储存,at 的资料是存放在所谓的 queue 中,使用者可以同时使用多个 queue,而 queue 的编号为 a, b, c... z 以及 A, B, ... Z 共 52 个
-m : 即使程式/指令执行完成后没有输出结果, 也要寄封信给使用者
-f file : 读入预先写好的命令档。使用者不一定要使用交谈模式来输入,可以先将所有的指定先写入档案后再一次读入
-l : 列出所有的指定 (使用者也可以直接使用 atq 而不用 at -l)
-d : 删除指定 (使用者也可以直接使用 atrm 而不用 at -d)
-v : 列出所有已经完成但尚未删除的指定

例子 :
三天后的下午 5 点锺执行 /bin/ls :
at 5pm + 3 days /bin/ls

三个星期后的下午 5 点锺执行 /bin/ls :
at 5pm + 2 weeks /bin/ls

明天的 17:20 执行 /bin/date :
at 17:20 tomorrow /bin/date

1999 年的最后一天的最后一分钟印出 the end of world !
at 23:59 12/31/1999 echo the end of world !

名称:cal

使用权限:所有使用者

使用方式:cal [-mjy] [month [year]]

说明:

显示日历。若只有一个参数,则代表年份(1-9999),显示该年的年历。年份必须全部写出:``cal 89 将不会是显示 1989 年的年历。使用两个参数,则表示月份及年份。若没有参数则显示这个月的月历。
1752 年 9 月第 3 日起改用西洋新历,因这时大部份的国家都采用新历,有 10 天被去除,所以该月份的月历有些不同。在此之前为西洋旧历。

匡兜

-m : 以星期一为每周的第一天方式显示。
-j : 以凯撒历显示,即以一月一日起的天数显示。
-y : 显示今年年历。

范例:

cal : 显示本月的月历。

[root@mylinux /root]# date
Tue Aug 15 08:00:18 CST 2000
[root@mylinux /root]# cal
August 2000
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

[root@mylinux /root]#

cal 2001 : 显示公元 2001 年年历。

[root@mylinux /root]# cal 2001
2001

January February March
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 1 2 3 1 2 3
7 8 9 10 11 12 13 4 5 6 7 8 9 10 4 5 6 7 8 9 10
14 15 16 17 18 19 20 11 12 13 14 15 16 17 11 12 13 14 15 16 17
21 22 23 24 25 26 27 18 19 20 21 22 23 24 18 19 20 21 22 23 24
28 29 30 31 25 26 27 28 25 26 27 28 29 30 31

April May June
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7 1 2 3 4 5 1 2
8 9 10 11 12 13 14 6 7 8 9 10 11 12 3 4 5 6 7 8 9
15 16 17 18 19 20 21 13 14 15 16 17 18 19 10 11 12 13 14 15 16
22 23 24 25 26 27 28 20 21 22 23 24 25 26 17 18 19 20 21 22 23
29 30 27 28 29 30 31 24 25 26 27 28 29 30

July August September
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 7 1 2 3 4 1
8 9 10 11 12 13 14 5 6 7 8 9 10 11 2 3 4 5 6 7 8
15 16 17 18 19 20 21 12 13 14 15 16 17 18 9 10 11 12 13 14 15
22 23 24 25 26 27 28 19 20 21 22 23 24 25 16 17 18 19 20 21 22
29 30 31 26 27 28 29 30 31 23 24 25 26 27 28 29
30
October November December
Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa Su Mo Tu We Th Fr Sa
1 2 3 4 5 6 1 2 3 1
7 8 9 10 11 12 13 4 5 6 7 8 9 10 2 3 4 5 6 7 8
14 15 16 17 18 19 20 11 12 13 14 15 16 17 9 10 11 12 13 14 15
21 22 23 24 25 26 27 18 19 20 21 22 23 24 16 17 18 19 20 21 22
28 29 30 31 25 26 27 28 29 30 23 24 25 26 27 28 29
30 31

[root@mylinux /root]#

cal 5 2001 : 显示公元 2001 年 5 月月历。

[root@mylinux /root]# cal 5 2001
May 2001
Su Mo Tu We Th Fr Sa
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

[root@mylinux /root]#

cal -m : 以星期一为每周的第一天方式,显示本月的月历。

[root@mylinux /root]# cal -m
August 2000
Mo Tu We Th Fr Sa Su
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31

[root@mylinux /root]#

cal -jy : 以一月一日起的天数显示今年的年历。

[root@mylinux /root]# cal -jy
2000

January February
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
1 32 33 34 35 36
2 3 4 5 6 7 8 37 38 39 40 41 42 43
9 10 11 12 13 14 15 44 45 46 47 48 49 50
16 17 18 19 20 21 22 51 52 53 54 55 56 57
23 24 25 26 27 28 29 58 59 60
30 31
March April
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
61 62 63 64 92
65 66 67 68 69 70 71 93 94 95 96 97 98 99
72 73 74 75 76 77 78 100 101 102 103 104 105 106
79 80 81 82 83 84 85 107 108 109 110 111 112 113
86 87 88 89 90 91 114 115 116 117 118 119 120
121
May June
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
122 123 124 125 126 127 153 154 155
128 129 130 131 132 133 134 156 157 158 159 160 161 162
135 136 137 138 139 140 141 163 164 165 166 167 168 169
142 143 144 145 146 147 148 170 171 172 173 174 175 176
149 150 151 152 177 178 179 180 181 182

July August
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
183 214 215 216 217 218
184 185 186 187 188 189 190 219 220 221 222 223 224 225
191 192 193 194 195 196 197 226 227 228 229 230 231 232
198 199 200 201 202 203 204 233 234 235 236 237 238 239
205 206 207 208 209 210 211 240 241 242 243 244
212 213
September October
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
245 246 275 276 277 278 279 280 281
247 248 249 250 251 252 253 282 283 284 285 286 287 288
254 255 256 257 258 259 260 289 290 291 292 293 294 295
261 262 263 264 265 266 267 296 297 298 299 300 301 302
268 269 270 271 272 273 274 303 304 305

November December
Sun Mon Tue Wed Thu Fri Sat Sun Mon Tue Wed Thu Fri Sat
306 307 308 309 336 337
310 311 312 313 314 315 316 338 339 340 341 342 343 344
317 318 319 320 321 322 323 345 346 347 348 349 350 351
324 325 326 327 328 329 330 352 353 354 355 356 357 358
331 332 333 334 335 359 360 361 362 363 364 365
366

[root@mylinux /root]#

名称 : crontab
使用权限 : 所有使用者

使用方式 :

crontab [ -u user ] filecrontab [ -u user ] { -l | -r | -e }
说明 :
crontab 是用来让使用者在固定时间或固定间隔执行程式之用,换句话说,也就是类似使用者的时程表。-u user 是指设定指定 user 的时程表,这个前提是你必须要有其权限(比如说是 root)才能够指定他人的时程表。如果不使用 -u user 的话,就是表示设定自己的时程表。

餐数 :

-e : 执行文字编辑器来设定时程表,内定的文字编辑器是 VI,如果你想用别的文字编辑器,则请先设定 VISUAL 环境变数来指定使用那个文字编辑器(比如说 setenv VISUAL joe)
-r : 删除目前的时程表
-l : 列出目前的时程表

时程表的格式如下 :
f1 f2 f3 f4 f5 program

其中 f1 是表示分钟,f2 表示小时,f3 表示一个月份中的第几日,f4 表示月份,f5 表示一个星期中的第几天。program 表示要执行的程式。
当 f1 为 * 时表示每分钟都要执行 program,f2 为 * 时表示每小时都要执行程式,其余类推
当 f1 为 a-b 时表示从第 a 分钟到第 b 分钟这段时间内要执行,f2 为 a-b 时表示从第 a 到第 b 小时都要执行,其余类推
当 f1 为 */n 时表示每 n 分钟个时间间隔执行一次,f2 为 */n 表示每 n 小时个时间间隔执行一次,其余类推
当 f1 为 a, b, c,... 时表示第 a, b, c,... 分钟要执行,f2 为 a, b, c,... 时表示第 a, b, c...个小时要执行,其余类推

使用者也可以将所有的设定先存放在档案 file 中,用 crontab file 的方式来设定时程表。
例子 :

每月每天每小时的第 0 分钟执行一次 /bin/ls :
0 7 * * * /bin/ls

在 12 月内, 每天的早上 6 点到 12 点中,每隔 20 分钟执行一次 /usr/bin/backup :
0 6-12/3 * 12 * /usr/bin/backup

周一到周五每天下午 5:00 寄一封信给 alex@domain.name :
0 17 * * 1-5 mail -s "hi" alex@domain.name < /tmp/maildata

每月每天的午夜 0 点 20 分, 2 点 20 分, 4 点 20 分....执行 echo "haha"
20 0-23/2 * * * echo "haha"

注意 :

当程式在你所指定的时间执行后,系统会寄一封信给你,显示该程式执行的内容,若是你不希望收到这样的信,请在每一行空一格之后加上 > /dev/null 2>&1 即可。

名称 : date
使用权限 : 所有使用者

使用方式 :

date [-u] [-d datestr] [-s datestr] [--utc] [--universal] [--date=datestr] [--set=datestr] [--help] [--version] [+FORMAT] [MMDDhhmm[[CC]YY][.ss]]

说明 :

date 可以用来显示或设定系统的日期与时间,在显示方面,使用者可以设定欲显示的格式,格式设定为一个加号后接数个标记,其中可用的标记列表如下 :

时间方面 :

% : 印出 %
%n : 下一行
%t : 跳格
%H : 小时(00..23)
%I : 小时(01..12)
%k : 小时(0..23)
%l : 小时(1..12)
%M : 分钟(00..59)
%p : 显示本地 AM 或 PM
%r : 直接显示时间 (12 小时制,格式为 hh:mm:ss [AP]M)
%s : 从 1970 年 1 月 1 日 00:00:00 UTC 到目前为止的秒数
%S : 秒(00..61)
%T : 直接显示时间 (24 小时制)
%X : 相当于 %H:%M:%S
%Z : 显示时区

日期方面 :
%a : 星期几 (Sun..Sat)
%A : 星期几 (Sunday..Saturday)
%b : 月份 (Jan..Dec)
%B : 月份 (January..December)
%c : 直接显示日期与时间
%d : 日 (01..31)
%D : 直接显示日期 (mm/dd/yy)
%h : 同 %b
%j : 一年中的第几天 (001..366)
%m : 月份 (01..12)
%U : 一年中的第几周 (00..53) (以 Sunday 为一周的第一天的情形)
%w : 一周中的第几天 (0..6)
%W : 一年中的第几周 (00..53) (以 Monday 为一周的第一天的情形)
%x : 直接显示日期 (mm/dd/yy)
%y : 年份的最后两位数字 (00.99)
%Y : 完整年份 (0000..9999)

若是不以加号作为开头,则表示要设定时间,而时间格式为 MMDDhhmm[[CC]YY][.ss],其中 MM 为月份,DD 为日,hh 为小时,mm 为分钟,CC 为年份前两位数字,YY 为年份后两位数字,ss 为秒数
把计 :

-d datestr : 显示 datestr 中所设定的时间 (非系统时间)
--help : 显示辅助讯息
-s datestr : 将系统时间设为 datestr 中所设定的时间
-u : 显示目前的格林威治时间
--version : 显示版本编号

例子 :
显示时间后跳行,再显示目前日期 :
date +%T%n%D

显示月份与日数 :
date +%B %d

显示日期与设定时间(12:34:56) :
date --date 12:34:56

注意 :

当你不希望出现无意义的 0 时(比如说 1999/03/07),则可以在标记中插入 - 符号,比如说 date +%-H:%-M:%-S 会把时分秒中无意义的 0 给去掉,像是原本的 08:09:04 会变为 8:9:4。另外,只有取得权限者(比如说 root)才能设定系统时间。

当你以 root 身分更改了系统时间之后,请记得以 clock -w 来将系统时间写入 CMOS 中,这样下次重新开机时系统时间才会持续抱持最新的正确值。

名称 : sleep
使用权限 : 所有使用者

使用方式 : sleep [--help] [--version] number[smhd]

说明 : sleep 可以用来将目前动作延迟一段时间

参数说明 :

--help : 显示辅助讯息
--version : 显示版本编号
number : 时间长度,后面可接 s、m、h 或 d
其中 s 为秒,m 为 分钟,h 为小时,d 为日数

例子 :
显示目前时间后延迟 1 分钟,之后再次显示时间 :
date;sleep 1m;date

名称: time
使用权限: 所有使用者

使用方式: time [options] COMMAND [arguments]

说明: time 指令的用途,在于量测特定指令执行时所需消耗的时间及系统资源等资讯。例如 CPU 时间、记忆体、输入输出等等。需要特别注意的是,部分资讯在 Linux 上显示不出来。这是因为在 Linux 上部分资源的分配函式与 time 指令所预设的方式并不相同,以致于 time 指令无法取得这些资料。

把计

-o or --output=FILE
设定结果输出档。这个选项会将 time 的输出写入 所指定的档案中。如果档案已经存在,系统将覆写其内容。
-a or --append
配合 -o 使用,会将结果写到档案的末端,而不会覆盖掉原来的内容。
-f FORMAT or --format=FORMAT
以 FORMAT 字串设定显示方式。当这个选项没有被设定的时候,会用系统预设的格式。不过你可以用环境变数 time 来设定这个格式,如此一来就不必每次登入系统都要设定一次。
一般设定上,你可以用
t
表示跳栏,或者是用
n
表示换行。每一项资料要用 % 做为前导。如果要在字串中使用百分比符号,就用 。(学过 C 语言的人大概会觉得很熟悉)
time 指令可以显示的资源有四大项,分别是:

Time resources
Memory resources
IO resources
Command info

详细的内容如下:

Time Resources
E 执行指令所花费的时间,格式是:[hour]:minute:second。请注意这个数字并不代表实际的 CPU 时间。
e 执行指令所花费的时间,单位是秒。请注意这个数字并不代表实际的 CPU 时间。
S 指令执行时在核心模式(kernel mode)所花费的时间,单位是秒。
U 指令执行时在使用者模式(user mode)所花费的时间,单位是秒。
P 执行指令时 CPU 的占用比例。其实这个数字就是核心模式加上使用者模式的 CPU 时间除以总时间。

Memory Resources
M 执行时所占用的实体记忆体的最大值。单位是 KB
t 执行时所占用的实体记忆体的平均值,单位是 KB
K 执行程序所占用的记忆体总量(stack+data+text)的平均大小,单位是 KB
D 执行程序的自有资料区(unshared data area)的平均大小,单位是 KB
p 执行程序的自有堆叠(unshared stack)的平均大小,单位是 KB
X 执行程序间共享内容(shared text)的平均值,单位是 KB
Z 系统记忆体页的大小,单位是 byte。对同一个系统来说这是个常数

IO Resources
F 此程序的主要记忆体页错误发生次数。所谓的主要记忆体页错误是指某一记忆体页已经置换到置换档(swap file)中,而且已经分配给其他程序。此时该页的内容必须从置换档里再读出来。
R 此程序的次要记忆体页错误发生次数。所谓的次要记忆体页错误是指某一记忆体页虽然已经置换到置换档中,但尚未分配给其他程序。此时该页的内容并未被破坏,不必从置换档里读出来
W 此程序被交换到置换档的次数
c 此程序被强迫中断(像是分配到的 CPU 时间耗尽)的次数
w 此程序自愿中断(像是在等待某一个 I/O 执行完毕,像是磁碟读取等等)的次数
I 此程序所输入的档案数
O 此程序所输出的档案数
r 此程序所收到的 Socket Message
s 此程序所送出的 Socket Message
k 此程序所收到的信号 ( Signal )数量

Command Info
C 执行时的参数以及指令名称
x 指令的结束代码 ( Exit Status )

-p or --portability
这个选项会自动把显示格式设定成为:
real %e
user %U
sys %S
这么做的目的是为了与 POSIX 规格相容。
-v or --verbose
这个选项会把所有程式中用到的资源通通列出来,不但如一般英文语句,还有说明。对不想花时间去熟习格式设定或是刚刚开始接触这个指令的人相当有用。

范例:
利用下面的指令
time -v ps -aux

我们可以获得执行 ps -aux 的结果和所花费的系统资源。如下面所列的资料:
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.4 1096 472 ? S Apr19 0:04 init
root 2 0.0 0.0 0 0 ? SW Apr19 0:00 [kflushd]
root 3 0.0 0.0 0 0 ? SW Apr19 0:00 [kpiod]
......
root 24269 0.0 1.0 2692 996 pts/3 R 12:16 0:00 ps -aux

Command being timed: "ps -aux"
User time (seconds): 0.05
System time (seconds): 0.06
Percent of CPU this job got: 68%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:00.16
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 238
Minor (reclaiming a frame) page faults: 46
Voluntary context switches: 0
Involuntary context switches: 0
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0

名称: uptime
使用权限: 所有使用者
使用方式: uptime [-V]
说明: uptime 提供使用者下面的资讯,不需其他参数:

现在的时间
系统开机运转到现在经过的时间
连线的使用者数量
最近一分钟,五分钟和十五分钟的系统负载
参数: -V 显示版本资讯。
范例: uptime
其结果为:
10:41am up 5 days, 10 min, 1 users, load average: 0.00, 0.00, 1.99

名称:chfn

使用权限:所有使用者

用法:shell>> chfn

说明:提供使用者更改个人资讯,用于 finger and mail username

范例:

shell>> chfn
Changing finger information for user
Password: [del]
Name[]:Johnney Huang ### 提供 finger 时的资料
Office[]:NCCU
Office Phone[]: [del]
Home Phone[]: [del]

名称:chsh

使用权限:所有使用者

用法:shell>> chsh

说明:更改使用者 shell 设定

范例:

shell>> chsh
Changing fihanging shell for user1
Password: [del]
New shell [/bin/tcsh]: ### [是目前使用的 shell]
[del]

shell>> chsh -l ### 展示 /etc/shells 档案内容
/bin/bash
/bin/sh
/bin/ash
/bin/bsh
/bin/tcsh
/bin/csh

” finger [返回]
名称: finger
使用权限: 所有使用者

使用方式: finger [options] user[@address]

说明:finger 可以让使用者查询一些其他使用者的资料。会列出来的资料有:

Login Name
User Name
Home directory
Shell
Login status
mail status
.plan
.project
.forward

其中 .plan ,.project 和 .forward 就是使用者在他的 Home Directory 里的 .plan , .project 和 .forward 等档案里的资料。如果没有就没有。finger 指令并不限定于在同一伺服器上查询,也可以寻找某一个远端伺服器上的使用者。只要给一个像是 E-mail address 一般的地址即可。
把计

-l
多行显示。

-s
单行显示。这个选项只显示登入名称,真实姓名,终端机名称,闲置时间,登入时间,办公室号码及电话号码。如果所查询的使用者是远端伺服器的使用者,这个选项无效。

范例:下列指令可以查询本机管理员的资料:
finger root

其结果如下:
Login: root Name: root
Directory: /root Shell: /bin/bash
Never logged in.
No mail.
No Plan.

名称:last

使用权限:所有使用者

使用方式:shell>> last [options]

说明:显示系统开机以来获是从每月初登入者的讯息

把计

-R 省略 hostname 的栏位
-num 展示前 num 个
username 展示 username 的登入讯息
tty 限制登入讯息包含终端机代号

范例:

shell>> last -R -2
johnney pts/1 Mon Aug 14 20:42 still logged in
johnney pts/0 Mon Aug 14 19:59 still logged in

wtmp begins Tue Aug 1 09:01:10 2000 ### /var/log/wtmp

shell>> last -2 minery
minery pts/0 140.119.217.115 Mon Aug 14 18:37 - 18:40 (00:03)
minery pts/0 140.119.217.115 Mon Aug 14 17:22 - 17:24 (00:02)

wtmp begins Tue Aug 1 09:01:10 2000

名称:login

这个命令都不会就不要干算了!呵呵我也不在这里多费笔墨耽误大家美好青春了^_^

名称:passwd

使用权限:所有使用者

使用方式:passwd [-k] [-l] [-u [-f]] [-d] [-S] [username]

说明:用来更改使用者的密码

参数:
-k

-l

-u

-f

-d 关闭使用者的密码认证功能, 使用者在登入时将可以不用输入密码, 只有具备 root 权限的使用者方可使用.

-S 显示指定使用者的密码认证种类, 只有具备 root 权限的使用者方可使用.

[username] 指定帐号名称.

名称 : who
使用权线 : 所有使用者都可使用

使用方式 : who - [husfV] [user]

说明 : 显示系统中有那些使用者正在上面,显示的资料包含了使用者 ID,使用的终端机,从那边连上来的,上线时间,呆滞时间,CPU 使用量,动作等等。

把计 :

-h : 不要显示标题列
-u : 不要显示使用者的动作/工作
-s : 使用简短的格式来显示
-f : 不要显示使用者的上线位置
-V : 显示程式版本
名称:/etc/aliases
使用权限:系统管理者
使用方式: 请用 newaliases 更新资料库
说明:
sendmail 会使用一个在 /etc/aliases 中的档案做使用者名称转换的动作。当 sendmail 收到一个要送给 xxx 的信时,它会依据 aliases档的内容送给另一个使用者。这个功能可以创造一个只有在信件系统内才有效的使用者。例如 mailing list 就会用到这个功能,在 mailinglist 中,我们可能会创造一个叫 redlinux@link.ece.uci.edu 的 mailinglist,但实际上并没有一个叫 redlinux 的使用者。实际 aliases 档的内容是将送给这个使用者的信都收给 mailing list 处理程式负责分送的工作。

/etc/aliases 是一个文字模式的档案,sendmail 需要一个二进位格式的 /etc/aliases.db。newaliases 的功能传是将 /etc/aliases 转换成一个 sendmail 所能了解的资料库。范例:
# newaliases

下面命令会做相同的事,
# sendmail -bi

相关命令:
mail, mailq, newaliases, sendmail

” mail [返回]
名称:mail

使用权限:所有使用者

使用方式:mail [-iInv] [-s subject] [-c cc-addr] [-b bcc-addr] user1 [user 2 ...]

说明:
mail 不仅只是一个指令, mail 还是一个电子邮件程式,不过利用 mail 来读信的人应该很少吧!对于系统管理者来说 mail 就很有用,因为管理者可以用 mail 写成 script ,定期寄一些备忘录提醒系统的使用者。

参数:
i 忽略 tty 的中断讯号。 (interrupt)
I 强迫设成互动模式。 (Interactive)
v 列印出讯息,例如送信的地点、状态等等。 (verbose)
n 不读入 mail.rc 设定档。
s 邮件标题。
c cc 邮件地址。
b bcc 邮件地址。

范例:

将信件送给一个或以上的电子邮件地址,由于没有加入其他的选项,使用者必须输入标题与信件的内容等。而 user2 没有主机位置,就会送给邮件伺服器的 user2 使用者。

mail user1@email.address
mail user1@email.address user2

将 mail.txt 的内容寄给 user2 同时 cc 给 user1 。如果将这一行指令设成 cronjob 就可以定时将备忘录寄给系统使用者。

mail -s 标题 -c user1 user2 < mail.txt

指令:mesg
使用权限 : 所有使用者

使用方式 : mesg [y|n]

说明 : 决定是否允许其他人传讯息到自己的终端机介面

把计 

y : 允许讯息传到终端机介面上。
n : 不允许讯息传到终端机介面上 。
如果没有设定,则讯息传递与否则由终端机界面目前状态而定。

例子 :
改变目前讯息设定,改成不允许讯息传到终端机介面上 :
mesg n

与 mesg 相关的指令有: talk,write,wall。

名称:/etc/aliases
使用权限:系统管理者
使用方式: newaliases
说明:
sendmail 会使用一个在 /etc/aliases 中的档案做使用者名称转换的动作。当 sendmail 收到一个要送给 xxx 的信时,它会依据 aliases档的内容送给另一个使用者。这个功能可以创造一个只有在信件系统内才有效的使用者。例如 mailing list 就会用到这个功能,在 mailinglist 中,我们可能会创造一个叫 redlinux@link.ece.uci.edu 的 mailinglist,但实际上并没有一个叫 redlinux 的使用者。实际 aliases 档的内容是将送给这个使用者的信都收给 mailing list 处理程式负责分送的工作。

/etc/aliases 是一个文字模式的档案,sendmail 需要一个二进位格式的 /etc/aliases.db。newaliases 的功能传是将 /etc/aliases 转换成一个 sendmail 所能了解的资料库。

参数:没有任何参数。 范例:
# newaliases

下面命令会做相同的事,
# sendmail -bi

相关命令:
mail, mailq, newaliases, sendmail

名称 : talk
使用权限 : 所有使用者

使用方式 :

talk person [ttyname]
说明 : 与其他使用者对谈

把计 :

person : 预备对谈的使用者帐号,如果该使用者在其他机器上,则可输入 person@machine.name
ttyname : 如果使用者同时有两个以上的 tty 连线,可以自行选择合适的 tty 传讯息

例子.1 :

与现在机器上的使用者Rollaend对谈,此时 Rollaend 只有一个连线 :
talk Rollaend

接下来就是等Rollaend回应,若Rollaend接受,则Rollaend输入 `talk jzlee`即可开始对谈,结束请按 ctrl+c

例子.2 :与linuxfab.cx上的使用者Rollaend对谈,使用pts/2来对谈 :
talk Rollaend@linuxfab.cx pts/2

接下来就是等Rollaend回应,若Rollaend接受,则Rollaend输入 `talk jzlee@jzlee.home`即可开始对谈,结束请按 ctrl+c

注意 : 若萤幕的字会出现不正常的字元,试着按 ctrl+l 更新萤幕画面。

名称 : wall
使用权限 : 所有使用者

使用方式 :

wall [ message ]
使用说明:
wall 会将讯息传给每一个 mesg 设定为 yes 的上线使用者。当使用终端机介面做为标准传入时, 讯息结束时需加上 EOF (通常用 Ctrl+D)

例子 :

传讯息"hi" 给每一个使用者 :
wall hi

名称 : write
使用权限 : 所有使用者

使用方式 :

write user [ttyname]
说明 : 传讯息给其他使用者

把计 :

user : 预备传讯息的使用者帐号
ttyname : 如果使用者同时有两个以上的 tty 连线,可以自行选择合适的 tty 传讯息

例子.1 :

传讯息给 Rollaend,此时 Rollaend 只有一个连线 :
write Rollaend

接下来就是将讯息打上去,结束请按 ctrl+c

例子.2 :传讯息给 Rollaend,Rollaend 的连线有 pts/2,pts/3 :
write Rollaend pts/2

接下来就是将讯息打上去,结束请按 ctrl+c

注意 : 若对方设定 mesg n,则此时讯席将无法传给对方

名称:kill
使用权限:所有使用者

使用方式:

kill [ -s signal | -p ] [ -a ] pid ...
kill -l [ signal ]
说明:kill 送出一个特定的信号 (signal) 给行程 id 为 pid 的行程根据该信号而做特定的动作, 若没有指定, 预设是送出终止 (TERM) 的信号
把计

-s (signal) : 其中可用的讯号有 HUP (1), KILL (9), TERM (15), 分别代表着重跑, 砍掉, 结束; 详细的信号可以用 kill -l
-p : 印出 pid , 并不送出信号
-l (signal) : 列出所有可用的信号名称
范例:

将 pid 为 323 的行程砍掉 (kill) :
kill -9 323

将 pid 为 456 的行程重跑 (restart) :
kill -HUP 456

名称:nice
使用权限:所有使用者

使用方式:nice [-n adjustment] [-adjustment] [--adjustment=adjustment] [--help] [--version] [command [arg...]]

说明:以更改过的优先序来执行程式, 如果未指定程式, 则会印出目前的排程优先序, 内定的 adjustment 为 10, 范围为 -20 (最高优先序) 到 19 (最低优先序)

把计

-n adjustment, -adjustment, --adjustment=adjustment 皆为将该原有优先序的增加 adjustment
--help 显示求助讯息
--version 显示版本资讯
范例:
将 ls 的优先序加 1 并执行 :
nice -n 1 ls

将 ls 的优先序加 10 并执行 :
nice ls将 ls 的优先序加 10 并执行

注意 : 优先序 (priority) 为作业系统用来决定 CPU 分配的参数,Linux 使用『回合制(round-robin)』的演算法来做 CPU 排程,优先序越高,所可能获得的 CPU时间就越多。

名称:ps
使用权限:所有使用者
使用方式:ps [options] [--help]
说明:显示瞬间行程 (process) 的动态
参数:
ps 的参数非常多, 在此仅列出几个常用的参数并大略介绍含义
-A 列出所有的行程
-w 显示加宽可以显示较多的资讯
-au 显示较详细的资讯
-aux 显示所有包含其他使用者的行程

au(x) 输出格式 :

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
USER: 行程拥有者
PID: pid
%CPU: 占用的 CPU 使用率
%MEM: 占用的记忆体使用率
VSZ: 占用的虚拟记忆体大小
RSS: 占用的记忆体大小
TTY: 终端的次要装置号码 (minor device number of tty)
STAT: 该行程的状态:
D: 不可中断的静止 (通悸□□缜b进行 I/O 动作)
R: 正在执行中
S: 静止状态
T: 暂停执行
Z: 不存在但暂时无法消除
W: 没有足够的记忆体分页可分配
<: 高优先序的行程
N: 低优先序的行程
L: 有记忆体分页分配并锁在记忆体内 (即时系统或捱A I/O)
START: 行程开始时间
TIME: 执行的时间
COMMAND:所执行的指令

范例:

ps
PID TTY TIME CMD
2791 ttyp0 00:00:00 tcsh
3092 ttyp0 00:00:00 ps
% ps -A
PID TTY TIME CMD
1 ? 00:00:03 init
2 ? 00:00:00 kflushd
3 ? 00:00:00 kpiod
4 ? 00:00:00 kswapd
5 ? 00:00:00 mdrecoveryd
.......
% ps -aux
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
root 1 0.0 0.7 1096 472 ? S Sep10 0:03 init [3]
root 2 0.0 0.0 0 0 ? SW Sep10 0:00 [kflushd]
root 3 0.0 0.0 0 0 ? SW Sep10 0:00 [kpiod]
root 4 0.0 0.0 0 0 ? SW Sep10 0:00 [kswapd]
........

名称:pstree
使用权限:所有使用者
使用方式:
pstree [-a] [-c] [-h|-Hpid] [-l] [-n] [-p] [-u] [-G|-U] [pid|user]
pstree -V
说明:将所有行程以树状图显示, 树状图将会以 pid (如果有指定) 或是以 init 这个基本行程为根 (root) ,如果有指定使用者 id , 则树状图会只显示该使用者所拥有的行程
参数:
-a 显示该行程的完整指令及参数, 如果是被记忆体置换出去的行程则会加上括号
-c 如果有重覆的行程名, 则分开列出 (预设值是会在前面加上 *
范例:

pstree

init-+-amd
|-apmd
|-atd
|-httpd---10*[httpd]
%pstree -p
init(1)-+-amd(447)
|-apmd(105)
|-atd(339)
%pstree -c
init-+-amd
|-apmd
|-atd
|-httpd-+-httpd
| |-httpd
| |-httpd
| |-httpd
....

名称:renice
使用权限:所有使用者

使用方式:renice priority [[-p] pid ...] [[-g] pgrp ...] [[-u] user ...]

说明:重新指定一个或多个行程(Process)的优先序(一个或多个将根据所下的参数而定)

把计

-p pid 重新指定行程的 id 为 pid 的行程的优先序
-g pgrp 重新指定行程群组(process group)的 id 为 pgrp 的行程 (一个或多个) 的优先序
-u user 重新指定行程拥有者为 user 的行程的优先序
范例:
将行程 id 为 987 及 32 的行程与行程拥有者为 daemon 及 root 的优先序号码加 1 :
renice +1 987 -u daemon root -p 32

注意 : 每一个行程(Process)都有一个唯一的 (unique) id

名称:top
使用权限:所有使用者

使用方式:top [-] [d delay] [q] [c] [S] [s] [i] [n] [b]

说明:即时显示 process 的动态

把计

d : 改变显示的更新速度,或是在交谈式指令列( interactive command)按 s
q : 没有任何延迟的显示速度,如果使用者是有 superuser 的权限,则 top 将会以最高的优先序执行
c : 切换显示模式,共有两种模式,一是只显示执行档的名称,另一种是显示完整的路径与名称S : 累积模式,会将己完成或消失的子行程 ( dead child process ) 的 CPU time 累积起来
s : 安全模式,将交谈式指令取消, 避免潜在的危机
i : 不显示任何闲置 (idle) 或无用 (zombie) 的行程
n : 更新的次数,完成后将会退出 top
b : 批次档模式,搭配 "n" 参数一起使用,可以用来将 top 的结果输出到档案内

范例:
显示更新十次后退出 ;
top -n 10

使用者将不能利用交谈式指令来对行程下命令 :
top -s

将更新显示二次的结果输入到名称为 top.log 的档案里 :
top -n 2 -b < top.log

名称:skill

使用权限:所有使用者

使用方式: skill [signal to send] [options] 选择程序的规则

说明:

送个讯号给正在执行的程序,预设的讯息为 TERM (中断) , 较常使用的讯息为 HUP , INT , KILL , STOP , CONT ,和 0

讯息有三种写法:分别为 -9 , -SIGKILL , -KILL , 可以使用 -l 或 -L 已列出可使用的讯息。

一般参数:

-f 快速模式/尚未完成

-i 互动模式/ 每个动作将要被确认

-v 详细输出/ 列出所选择程序的资讯

-w 智能警告讯息/ 尚未完成

-n 没有动作/ 显示程序代号

参数:选择程序的规则可以是, 终端机代号,使用者名称,程序代号,命令名称。

-t 终端机代号 ( tty 或 pty )

-u 使用者名称

-p 程序代号 ( pid )

-c 命令名称 可使用的讯号:

以下列出已知的讯号名称,讯号代号,功能。

名称 (代号) 功能/ 描述

ALRM 14 离开

HUP 1 离开

INT 2 离开

KILL 9 离开/ 强迫关闭

PIPE 13 离开

POLL 离开

PROF 离开

TERM 15 离开

USR1 离开

USR2 离开

VTALRM 离开

STKFLT 离开/ 只适用于i386, m68k, arm 和 ppc 硬体

UNUSED 离开/ 只适用于i386, m68k, arm 和 ppc 硬体

TSTP 停止 /产生与内容相关的行为

TTIN 停止 /产生与内容相关的行为

TTOU 停止 /产生与内容相关的行为

STOP 停止 /强迫关闭

CONT 从新启动 /如果在停止状态则从新启动,否则忽略

PWR 忽略 /在某些系统中会离开

WINCH 忽略

CHLD 忽略

ABRT 6 核心

FPE 8 核心

ILL 4 核心

QUIT 3 核心

SEGV 11 核心

TRAP 5 核心

SYS 核心 /或许尚未实作

EMT 核心 /或许尚未实作

BUS 核心 /核心失败

XCPU 核心 /核心失败

XFSZ 核心 /核心失败

范例:

停止所有在 PTY 装置上的程序
skill -KILL -v pts/*

停止三个使用者 user1 , user2 , user3
skill -STOP user1 user2 user3

其他相关的命令: kill
名称:expr

使用权限:所有使用者
### 字串长度

shell>> expr length "this is a test"
14

### 数字商数

shell>> expr 14 % 9
5

### 从位置处抓取字串

shell>> expr substr "this is a test" 3 5
is is

### 数字串 only the first character

shell>> expr index "testforthegame" e
2

### 字串真实重现

shell>> expr quote thisisatestformela
thisisatestformela

名称: tr

### 1.比方说要把目录下所有的大写档名换为小写档名?

似乎有很多方式,"tr"是其中一种:

#!/bin/sh

dir="/tmp/testdir";
files=`find $dir -type f`;
for i in $files
do
dir_name=`dirname $i`;
ori_filename=`basename $i`
new_filename=`echo $ori_filename | tr [:upper:] [:lower:]` > /dev/null;
#echo $new_filename;
mv $dir_name/$ori_filename $dir_name/$new_filename
done

### 2.自己试验中...lowercase to uppercase

tr abcdef...[del] ABCDE...[del]
tr a-z A-Z
tr [:lower:] [:upper:]

shell>> echo "this is a test" | tr a-z A-Z > www
shell>> cat www
THIS IS A TEST

### 3.去掉不想要的字串

shell>> tr -d this ### 去掉有关 t.e.s.t
this

man
man
test
e

### 4.取代字串

shell>> tr -s "this" "TEST"
this
TEST
th
TE

指令:clear
用途:清除萤幕用。

使用方法:在 console 上输入 clear。

名称: reset, tset
使用方法: tset [-IQqrs] [-] [-e ch] [-i ch] [-k ch] [-m mapping] [terminal]

使用说明:

reset 其实和 tset 是一同个命令,它的用途是设定终端机的状态。一般而言,这个命令会自动的从环境变数、命令列或是其它的组态档决定目前终端机的型态。如果指定型态是 ? 的话,这个程式会要求使用者输入终端机的型别。

由于这个程式会将终端机设回原始的状态,除了在 login 时使用外,当系统终端机因为程式不正常执行而进入一些奇怪的状态时,你也可以用它来重设终端机o 例如不小心把二进位档用 cat 指令进到终端机,常会有终端机不再回应键盘输入,或是回应一些奇怪字元的问题。此时就可以用 reset 将终端机回复至原始状态。选项说明:

-p
将终端机类别显示在萤幕上,但不做设定的动作。这个命令可以用来取得目前终端机的类别。
-e ch
将 erase 字元设成 ch
-i ch
将中断字元设成 ch
-k ch
将删除一行的字元设成 ch
-I
不要做设定的动作,如果没有使用选项 -Q 的话,erase、中断及删除字元的目前值依然会送到萤幕上。
-Q
不要显示 erase、中断及删除字元的值到萤幕上。
-r
将终端机类别印在萤幕上。
-s
将设定 TERM 用的命令用字串的型式送到终端机中,通常在 .login 或 .profile 中用
范例:
让使用者输入一个终端机型别并将终端机设到该型别的预设状态。
# reset ?

将 erase 字元设定 control-h
# reset -e ^B

将设定用的字串显示在萤幕上
# reset -s
Erase is control-B (^B).
Kill is control-U (^U).
Interrupt is control-C (^C).
TERM=xterm;

名称:compress

使用权限:所有使用者

使用方式:compress [-dfvcV] [-b maxbits] [file ...]

说明:
compress 是一个相当古老的 unix 档案压缩指令,压缩后的档案会加上一个 .Z 延伸档名以区别未压缩的档案,压缩后的档案可以以 uncompress 解压。若要将数个档案压成一个压缩档,必须先将档案 tar 起来再压缩。由于 gzip 可以产生更理想的压缩比例,一般人多已改用 gzip 为档案压缩工具。

参数:
c 输出结果至标准输出设备(一般指荧幕)
f 强迫写入档案,若目的档已经存在,则会被覆盖 (force)
v 将程式执行的讯息印在荧幕上 (verbose)
b 设定共同字串数的上限,以位元计算,可以设定的值为 9 至 16 bits 。由于值越大,能使用的共同字串就 越多,压缩比例就越大,所以一般使用预设值 16 bits (bits)
d 将压缩档解压缩
V 列出版本讯息

范例:

将 source.dat 压缩成 source.dat.Z ,若 source.dat.Z 已经存在,内容则会被压缩档覆盖。

compress -f source.dat

将 source.dat 压缩成 source.dat.Z ,并列印出压缩比例。
-v 与 -f 可以一起使用

compress -vf source.dat

将压缩后的资料输出后再导入 target.dat.Z 可以改变压缩档名。

compress -c source.dat > target.dat.Z

-b 的值越大,压缩比例就越大,范围是 9-16 ,预设值是 16 。

compress -b 12 source.dat

将 source.dat.Z 解压成 source.dat ,若档案已经存在,使用者按 y 以确定覆盖档案,若使用 -df 程式则会自动覆盖档案。由于系统会自动加入 .Z 为延伸档名,所以 source.dat 会自动当作 source.dat.Z 处理。

compress -d source.dat
compress -d source.dat.Z

名称: lpd

使用权限: 所有使用者

使用方式:lpd [-l] [#port]
lpd 是一个常驻的印表机管理程式,它会根据 /etc/printcap 的内容来管理本地或远端的印表机。/etc/printcap 中定义的每一个印表机必须在 /var/lpd 中有一个相对应的目录,目录中以 cf 开头的档案表示一个等待送到适当装置的印表工作。这个档案通常是由 lpr 所产生。

lpr 和 lpd 组成了一个可以离线工作的系统,当你使用 lpr 时,印表机不需要能立即可用,甚至不用存在。lpd 会自动监视印表机的状况,当印表机上线后,便立即将档案送交处理。这个得所有的应用程式不必等待印表机完成前一工作。

参数:

-l: 将一些除错讯息显示在标准输出上。
#port: 一般而言,lpd 会使用 getservbyname 取得适当的 TCP/IP port,你可以使用这个参数强迫 lpd 使用指定的 port。

范例:
这个程式通常是由 /etc/rc.d 中的程式在系统启始阶段执行。

名称 lpq
-- 显示列表机贮列中未完成的工作 用法

lpq [l] [P] [user]

说明
lpq 会显示由 lpd 所管理的列表机贮列中未完成的项目。

范例
范例 1. 显示所有在 lp 列表机贮列中的工作

# lpq -PlpRank Owner Job Files Total Size1st root 238 (standard input) 1428646 bytes

相关函数
lpr,lpc,lpd

名称: lpr

使用权限: 所有使用者

使用方式:lpr [ -P printer ]
将档案或是由标准输入送进来的资料送到印表机贮列之中,印表机管理程式 lpd 会在稍后将这个档案送给适当的程式或装置处理。lpr 可以用来将料资送给本地或是远端的主机来处理。

参数:

-p Printer: 将资料送至指定的印表机 Printer,预设值为 lp。

范例:
将 www.c 和 kkk.c 送到印表机 lp。
lpr -Plp www.c kkk.c

名称: lprm
-- 将一个工作由印表机贮列中移除 用法

/usr/bin/lprm [P] [file...]

说明
尚未完成的印表机工作会被放在印表机贮列之中,这个命令可用来将常未送到印表机的工作取消。由于每一个印表机都有一个独立的贮列,你可以用 -P 这个命令设定想要作用的印列机。如果没有设定的话,会使用系统预设的印表机。

这个命令会检查使用者是否有足够的权限删除指定的档案,一般而言,只有档案的拥有者或是系统管理员才有这个权限。

范例
将印表机 hpprinter 中的第 1123 号工作移除

lprm -Phpprinter 1123

将第 1011 号工作由预设印表机中移除

lprm 1011

名称: fdformat

使用权限: 所有使用者

使用方式:fdformat [-n] device

使用说明 :
对指定的软碟机装置进行低阶格式化。使用这个指令对软碟格式化的时候,最好指定像是下面的装置:

/dev/fd0d360 磁碟机 A: ,磁片为 360KB 磁碟
/dev/fd0h1440 磁碟机 A: ,磁片为 1.4MB 磁碟
/dev/fd1h1200 磁碟机 B: ,磁片为 1.2MB 磁碟
如果使用像是 /dev/fd0 之类的装置,如果里面的磁碟不是标准容量,格式化可能会失败。在这种情况之下,使用者可以用 setfdprm 指令先行指定必要参数。

参数:

-n 关闭确认功能。这个选项会关闭格式化之后的确认步骤。

范例:

fdformat -n /dev/fd0h1440

将磁碟机 A 的磁片格式化成 1.4MB 的磁片。并且省略确认的步骤。

名称: mformat

使用权限: 所有使用者

使用方式:

mformat [-t cylinders] [-h heads] [-s sectors] [-l volume_label] [-F] [-I fsVer-sion] [-S sizecode] [-2 sectors_on_track_0] [-M software_sector_size] [-a] [-X] [-C] [-H hidden_sectors] [-r root_sectors] [-B boot_sector] [-0 rate_on_track_0] [-A rate_on_other_tracks] [-1] [-k] drive:

在已经做过低阶格式化的磁片上建立 DOS 档案系统。如果在编译 mtools 的时候把 USE_2M 的参数打开,部分与 2M 格式相关的参数就会发生作用。否则这些参数(像是 S,2,1,M)不会发生作用。

参数:

-t 磁柱(synlider)数
-h 磁头(head)数
-s 每一磁轨的磁区数
-l 标签
-F 将磁碟格式化为 FAT32 格式,不过这个参数还在实验中。
-I 设定 FAT32 中的版本号。这当然也还在实验中。
-S 磁区大小代码,计算方式为 sector = 2^(大小代码+7)
-c 磁丛(cluster)的磁区数。如果所给定的数字会导致磁丛数超过 FAT 表的限制,mformat 会自动放大磁区数。
-s
-M 软体磁区大小。这个数字就是系统回报的磁区大小。通常是和实际的大小相同。
-a 如果加上这个参数,mformat 会产生一组 Atari 系统的序号给这块软碟。
-X 将软碟格式化成 XDF 格式。使用前必须先用 xdfcopy 指令对软碟作低阶格式化的动作。
-C 产生一个可以安装 MS-DOS 档案系统的磁碟影像档(disk image)。当然对一个实体磁碟机下这个参数是没有意义的。
-H 隐藏磁区的数目。这通常适用在格式化硬碟的分割区时,因为通常一个分割区的前面还有分割表。这个参数未经测试,能不用就不用。
-n 磁碟序号
-r 根目录的大小,单位是磁区数。这个参数只对 FAT12 和 FAT16 有效。
-B 使用所指定的档案或是设备的开机磁区做为这片磁片或分割区的开机磁区。当然当中的硬体参数会随之更动。
-k 尽量保持原有的开机磁区。
-0 第 0 轨的资料传输率
-A 第 0 轨以外的资料传输率
-2 使用 2m 格式
-1 不使用 2m 格式

范例:
mformat a:

这样会用预设值把 a: (就是 /dev/fd0)里的磁碟片格式化。

名称: mkdosfs

使用权限: 所有使用者

使用方式: mkdosfs [ -c | -l filename ]
[ -f number_of_FATs ]
[ -F FAT_size ]
[ -i volume_id ]
[ -m message_file ]
[ -n volume_name ]
[ -r root_dir_entry ]
[ -s sector_per_cluster ]
[ -v ]
device
[ block_count ]

说明: 建立 DOS 档案系统。 device 指你想要建立 DOS 档案系统的装置代号。像是 /dev/hda1 等等。 block_count 则是你希望配置的区块数。如果 block_count 没有指定则系统会自动替你计算符合该装置大小的区块数。

参数:

-c 建立档案系统之前先检查是否有坏轨。
-l 从得定的档案中读取坏轨记录。
-f 指定档案配置表(FAT , File Allocation Table)的数量。预设值为 2 。目前 Linux 的 FAT 档案系统不支援超过 2 个 FAT 表。通常这个不需要改。
-F 指定 FAT 表的大小,通常是 12 或是 16 个位元组。12 位元组通常用于磁碟片,16 位元组用于一般硬碟的分割区,也就是所谓的 FAT16 格式。这个值通常系统会自己选定适当的值。在磁碟片上用 FAT16 通常不会发生作用,反之在硬碟上用 FAT12 亦然。
-i 指定 Volume ID。一般是一个 4 个位元组的数字,像是 2e203a47 。如果不给系统会自己产生。
-m 当使用者试图用这片磁片或是分割区开机,而上面没有作业系统时,系统会给使用者一段警告讯息。这个参数就是用来变更这个讯息的。你可以先用档案编辑好,然后用这个参数指定,或是用
-m -
这样系统会要求你直接输入这段文字。要特别注意的是,档案里的字串长度不要超过 418 个字,包括展开的跳栏符号(TAB)和换行符号(换行符号在 DOS 底下算两个字元!)
-n 指定 Volume Name,就是磁碟标签。如同在 DOS 底下的 format 指令一样,给不给都可以。没有预设值。
-r 指定根目录底下的最大档案数。这里所谓的档案数包括目录。预设值是在软碟上是 112 或是 224 ,在硬碟上是 512。没事不要改这个数字。
-s 每一个磁丛(cluster)的磁区数。必须是 2 的次方数。不过除非你知道你在作什么,这个值不要乱给。
-v 提供额外的讯息

范例:
mkdosfs -n Tester /dev/fd0 将 A 槽里的磁碟片格式化为 DOS 格式,并将标签设为 Tester

发表在 article | 标签为 | 31条评论

apache、lighttpd和Nginx的404错误处理

最近在处理图片分布问题,问题来源是这样的:
1 把服务器B的图片定时同步到服务器A,用A来接受用户访问
2 同步有时间差,为了保证用户体验,需要在A发生404错误的时候转移到原服务器B,这样用户体会不到发生问题,否则上传图片会立刻看不到,不可能等你同步完的

我觉得这样的分布方式应该是很不错的,只要解决404错误的处理,就可以保证上面的服务正常。因为是说明问题,所以以下提及的代码都整理过,域名也做了更改。

一、最初用lighttpd来处理:

发生404错误,则交由cgi脚本来处理,取得$REQUEST_URI,location到源服务器

404.cgi脚本文件(比较简单,需要条件性的转移请自行修改):

 

#!/bin/sh

# disable filename globbing
set -f

URI=$REQUEST_URI

## by hqlulu @ aslibra.com 2008-8-14 ##
echo "location: http://www.aslibra.com$URI"
echo

Lighttpd下使用cgi测试:

 

#配置如下:
server.error-handler-404 = "/cgi-bin/404.cgi"

http://test404.aslibra.com/mag/nofile
得到的是www.aslibra.com的404错误提示,说明已经转移成功

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com/mag/nofile
HTTP/1.1 302 Found
Expires: Tue, 02 Sep 2008 12:52:44 GMT
Cache-Control: max-age=864000
location: http://www.aslibra.com/mag/nofile
Date: Sat, 23 Aug 2008 12:52:44 GMT
Server: lighttpd/1.4.15

二、Apache安装在8080端口,尝试cgi失败了:

 

#配置如下:
ErrorDocument 404 "/cgi-bin/404.cgi"

http://test404.aslibra.com:8080/mag/nofile
看到的是空白页面

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com:8080/mag/nofile
HTTP/1.1 404 Not Found
Date: Sat, 23 Aug 2008 12:55:45 GMT
Server: Apache/2.2.6 (Unix)
location: http://www.aslibra.com/mag/nofile
Connection: close
Content-Type: text/plain

琢磨了很久,才发现问题,可以看到原因,已经发出了404错误的文件头了,导致后面的location失效,但是怎么去掉404的输出呢,让我纳闷了很久。

经过查实Apache的文档:

 

引用
如果ErrorDocument指定了一个到本地CGI脚本的重定向,该脚本应当在它的输出中包含一个"Status:"头字段以确保将导致调用它的错误条件始终返回客户端。举例来说,一个Perl ErrorDocument脚本可能包含如下内容:

print "Content-type: text/html\n";
printf "Status: %s <中断条件>\n", $ENV{"REDIRECT_STATUS"};

如果该脚本专门用于处理一个特定的错误条件,比如:404 Not Found ,它就可以使用特定的代码和错误文本进行替代。

需要注意的是如果应答包含一个"Location:"头(为了进行一个客户端重定向),脚本必须发出一个适当的"Status:"头(比如:302 Found)。否则"Location:"头可能无效。

这就找到原因了,加上一段就可以了:

 

#!/bin/sh

# disable filename globbing
set -f

URI=$REQUEST_URI
echo "Status:302 Found"

## by hqlulu @ aslibra.com 2008-8-14 ##
echo "location: http://www.aslibra.com$URI"
echo

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com:8080/mag/nofile
HTTP/1.1 302 Found
Date: Sat, 23 Aug 2008 13:02:54 GMT
Server: Apache/2.2.6 (Unix)
location: http://www.aslibra.com/mag/nofile
Connection: close
Content-Type: text/plain

三、Apache的PHP处理方式(安装了PHP的模块):

 

ErrorDocument 404 /404.php

404.php文件内容(条件转移自行修改):
 

<?php
$url=$_SERVER[REQUEST_URI];
header("location: http://www.aslibra.com".$url);
?>

测试结果:
 

引用
[root@gx ~]# curl -I http://pic.zcom.com/mag/nofile
HTTP/1.1 302 Found
Date: Sat, 23 Aug 2008 13:10:14 GMT
Server: Apache/2.2.6 (Unix) PHP/5.2.6
X-Powered-By: PHP/5.2.6
location: http://www.aslibra.com/mag/nofile
Content-Type: text/html

四、Nginx的配置:

因为Nginx没法使用cgi,只能使用fastcgi,所以配置了PHP的fastcgi处理404错误。

 

error_page  404              /404.php;

location ~ \.php$ {
    fastcgi_pass   192.168.1.5:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /Data/webapps/www.aslibra.com$fastcgi_script_name;
    include        fastcgi_params;
}

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com:88/mag/nofile
HTTP/1.1 404 Not Found
Server: nginx/0.6.31
Date: Sat, 23 Aug 2008 13:10:42 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.2.6
location: http://www.aslibra.com/mag/nofile

碰到了apache的一样的问题,于是查看官方说明的错误处理:

 

引用
error_page
syntax: error_page code [ code... ] [ = |=answer-code ] uri

default: no

context: http, server, location, if in location

The directive specifies the URI, which will be showed for the errors indicated.

Example of the use:

error_page   404          /404.html;
error_page   502 503 504  /50x.html;
error_page   403          http://example.com/forbidden.html;
Furthermore, it is possible to change the code of answer to another, for example:

error_page 404 =200 /.empty.gif;
If an erroneous answer is processed by the proxied or FastCGI server and this server can return the different answer codes, for example, 200, 302, 401 or 404, then it is possible to issue the code returned:

error_page   404  =  /404.php;

终于看到这个例子了:
error_page 404 =200 /.empty.gif;

也就是指定一个answer-code就正常了,修改配置:
 

error_page  404 =302             /404.php;

location ~ \.php$ {
    fastcgi_pass   192.168.1.5:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  /Data/webapps/www.aslibra.com$fastcgi_script_name;
    include        fastcgi_params;
}

测试结果:
 

引用
[root@gx ~]# curl -I http://test404.aslibra.com:88/mag/nofile
HTTP/1.1 302 Moved Temporarily
Server: nginx/0.6.31
Date: Sat, 23 Aug 2008 13:15:20 GMT
Content-Type: text/html
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.2.6
location: http://www.aslibra.com/mag/nofile

这回就正常了!

以上是常见的三种web服务器的404错误处理,希望可以对解决大家的应用问题有参考价值。

五、404.cgi的条件判断(代码有点笨,sh不是专长):

 

#!/bin/sh

# disable filename globbing
set -f

URI=$REQUEST_URI
echo "Status:302 Found"

if
  echo $URI | grep "^/mag" >/dev/null
then
        echo "location: http://www1.aslibra.com$URI"
elif
  echo $URI | grep "^/op" >/dev/null
then
        echo "location: http://www2.aslibra.com$URI"
else
        echo
        echo "file not exists!"
fi

发表在 web server | 标签为 , , | apache、lighttpd和Nginx的404错误处理已关闭评论

Nginx 0.5.33 + PHP 5.2.5 (FastCGI) 可以承受3万以上的并发连接数,相当于同等环境下Apache的10倍

根据我的经验,4GB内存的服务器+Apache(prefork模式)一般只能处理3000个并发连接,因为它们将占用3GB以上的内存,还得为系统预留1GB的内存。我曾经就有两台Apache服务器,因为在配置文件中设置的MaxClients为4000,当Apache并发连接数达到3800时,导致服务器内存和Swap空间用满而崩溃。

  而这台 Nginx 0.5.33 + PHP 5.2.5 (FastCGI) 服务器在3万并发连接下,开启的10个Nginx进程消耗150M内存(15M*10=150M),开启的64个php-cgi进程消耗1280M内存(20M*64=1280M),加上系统自身消耗的内存,总共消耗不到2GB内存。如果服务器内存较小,完全可以只开启25个php-cgi进程,这样php-cgi消耗的总内存数才500M。

 


  安装步骤:
  (系统要求:Linux 2.6+ 内核,本文中的Linux操作系统为CentOS 4.4)

  一、获取相关开源程序:
  1、下载程序源码包到当前目录:
  本文中提到的所有开源软件为截止到2007年11月25日的最新稳定版。我将它们打了两个压缩包。

  第一个压缩包:nginx-php-1.zip
  下载地址:http://ishare.iask.sina.com.cn/cgi-bin/fileid.cgi?fileid=2746375

  第二个压缩包:nginx-php-2.zip
  下载地址:http://ishare.iask.sina.com.cn/cgi-bin/fileid.cgi?fileid=2746370

  附:各开源软件单独下载地址(如果下载了以上两个压缩包,则无需下载以下软件):
  http://down.s135.com/linux/nginx-php/
(登录用户名、密码均为blog.s135.com)

  2、解压缩:
 

mkdir -p /data0/software
cd /data0/software
unzip nginx-php-1.zip
unzip nginx-php-2.zip
cd /data0/software/nginx-php

 


  二、安装PHP 5.2.5(FastCGI模式)
  1、编译安装PHP 5.2.5所需的支持库:
 

tar zxvf libiconv-1.11.tar.gz
cd libiconv-1.11/
./configure --prefix=/usr/local
make
make install
cd ../

tar zxvf freetype-2.3.5.tar.gz
cd freetype-2.3.5/
./configure
make
make install
cd ../

tar zxvf libpng-1.2.20.tar.gz
cd libpng-1.2.20/
./configure
make
make install
cd ../

tar zxvf jpegsrc.v6b.tar.gz
cd jpeg-6b/
./configure --enable-static --enable-shared
make
make install
make install-lib
cd ../

#----If your system was install libxml2, you do not need to install it.----
#tar zxvf libxml2-2.6.30.tar.gz
#cd libxml2-2.6.30/
#./configure
#make
#install
#cd ../

tar zxvf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8/
./configure
make
make install
/sbin/ldconfig
cd libltdl/
./configure --enable-ltdl-install
make
make install
cd ../../

tar zxvf mhash-0.9.9.tar.gz
cd mhash-0.9.9/
./configure
make
make install
cd ../

cp /usr/local/lib/libmcrypt.* /usr/lib
ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2

tar zxvf mcrypt-2.6.6.tar.gz
cd mcrypt-2.6.6/
./configure
make
make install
cd ../

 


  2、编译安装MySQL 5.0.45
 

/usr/sbin/groupadd mysql
/usr/sbin/useradd -g mysql mysql
tar zxvf mysql-5.0.45.tar.gz
cd mysql-5.0.45
./configure --prefix=/usr/local/webserver/mysql/ --without-debug --with-unix-socket-path=/tmp/mysql.sock --with-client-ldflags=-all-static --with-mysqld-ldflags=-all-static --enable-assembler --with-extra-charsets=gbk,gb2312,utf8 --with-pthread --enable-thread-safe-client
make && make install
chmod +w /usr/local/webserver/mysql
chown -R mysql:mysql /usr/local/webserver/mysql
cp support-files/my-medium.cnf /usr/local/webserver/mysql/my.cnf
cd ../

 


  附:以下为附加步骤,如果你想在这台服务器上运行MySQL数据库,则执行以下两步。如果你只是希望让PHP支持MySQL扩展库,能够连接其他服务器上的MySQL数据库,那么,以下两步无需执行。
  ①、以mysql用户帐号的身份建立数据表:
 

/usr/local/webserver/mysql/bin/mysql_install_db --defaults-file=/usr/local/webserver/mysql/my.cnf --basedir=/usr/local/webserver/mysql --datadir=/usr/local/webserver/mysql/data --user=mysql --pid-file=/usr/local/webserver/mysql/mysql.pid --skip-locking --port=3306 --socket=/tmp/mysql.sock

  ②、启动MySQL(最后的&表示在后台运行)
 

/bin/sh /usr/local/webserver/mysql/bin/mysqld_safe --defaults-file=/usr/local/webserver/mysql/my.cnf &

 


  3、编译安装PHP(FastCGI模式)
 

tar zxvf php-5.2.5.tar.gz
cd php-5.2.5/
./configure --prefix=/usr/local/webserver/php --with-config-file-path=/usr/local/webserver/php/etc --with-mysql=/usr/local/webserver/mysql --with-iconv-dir=/usr/local --with-freetype-dir --with-jpeg-dir --with-png-dir --with-zlib --with-libxml-dir --enable-xml --disable-debug --disable-rpath --enable-discard-path --enable-safe-mode --enable-bcmath --enable-shmop --enable-sysvsem --enable-inline-optimization --with-curl --with-curlwrappers --enable-mbregex --enable-fastcgi --enable-force-cgi-redirect --enable-mbstring --with-mcrypt
sed -i 's#-lz -lm -lxml2 -lz -lm -lxml2 -lz -lm -lcrypt#& -liconv#' Makefile
make
make install
cp php.ini-dist /usr/local/webserver/php/etc/php.ini
cd ../

 


  4、编译安装PHP5扩展模块
 

tar zxvf memcache-2.2.1.tgz
cd memcache-2.2.1/
/usr/local/webserver/php/bin/phpize
./configure --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../

cd php-5.2.5/ext/gd/
/usr/local/webserver/php/bin/phpize
./configure --with-jpeg-dir --with-png-dir --with-zlib-dir --with-ttf --with-freetype-dir --with-php-config=/usr/local/webserver/php/bin/php-config
make
make install
cd ../../../

  5、修改php.ini文件
  手工修改:查找/usr/local/webserver/php/etc/php.ini中的extension_dir = "./"
  修改为extension_dir = "/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/"
  并在此行后增加以下几行,然后保存:
  extension = "memcache.so"
  extension = "gd.so"

  自动修改:若嫌手工修改麻烦,可执行以下shell命令,自动完成对php.ini文件的修改:
 

sed -i 's#extension_dir = "./"#extension_dir = "/usr/local/webserver/php/lib/php/extensions/no-debug-non-zts-20060613/"\nextension = "memcache.so"\nextension = "gd.so"\n#' /usr/local/webserver/php/etc/php.ini

 


  6、创建www用户和组,以及其使用的目录:
 

/usr/sbin/groupadd www -g 48
/usr/sbin/useradd -u 48 -g www www
mkdir -p /data0/vshare/htdocs
chmod +w /data0/vshare/htdocs
chown -R www:www /data0/vshare/htdocs

  7、安装lighttpd中附带的spawn-fcgi,用来启动php-cgi
  注:压缩包中的spawn-fcgi程序为已经编译成二进制的版本。
 

cp spawn-fcgi /usr/local/webserver/php/bin
chmod +x /usr/local/webserver/php/bin/spawn-fcgi

  8、启动php-cgi进程,监听127.0.0.1的10080端口,进程数为64(如果服务器内存小于3GB,可以只开启25个进程),用户为www:
 

/usr/local/webserver/php/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 64 -u www -f /usr/local/webserver/php/bin/php-cgi

 


  三、安装Nginx 0.5.33
  1、安装Nginx所需的pcre库:
 

tar zxvf pcre-7.2.tar.gz
cd pcre-7.2/
./configure
make && make install
cd ../

  2、安装Nginx
 

tar zxvf nginx-0.5.33.tar.gz
cd nginx-0.5.33/
./configure --user=www --group=www --prefix=/usr/local/webserver/nginx --with-http_stub_status_module
make && make install
cd ../

  3、创建Nginx日志目录
 

mkdir -p /data1/logs
chmod +w /data1/logs
chown -R www:www /data1/logs

  4、创建Nginx配置文件
  ①、在/usr/local/webserver/nginx/conf/目录中创建nginx.conf文件:
 

rm -f /usr/local/webserver/nginx/conf/nginx.conf
vi /usr/local/webserver/nginx/conf/nginx.conf

  输入以下内容:
 

引用
user  www www;

worker_processes 10;

error_log  /data1/logs/nginx_error.log  crit;

#pid        logs/nginx.pid;

#Specifies the value for maximum file descriptors that can be opened by this process.
worker_rlimit_nofile 51200;

events
{
      use epoll;

      worker_connections 51200;
}

http
{
      include       conf/mime.types;
      default_type  application/octet-stream;

      charset  gb2312;
     
      server_names_hash_bucket_size 128;
     
      #sendfile on;
      #tcp_nopush     on;

      keepalive_timeout 60;

      tcp_nodelay on;

      gzip on;
      gzip_min_length  1k;
      gzip_buffers     4 8k;
      gzip_http_version 1.1;
      gzip_types       text/plain application/x-javascript text/css text/html application/xml;

      server
      {
              listen       80;
              server_name  blog.s135.com;
              index index.html index.htm index.php;
              root  /data0/vshare/htdocs;

              if (-d $request_filename)
              {
                     rewrite ^/(.*)([^/])$ http://$host/$1$2/
permanent;
              }
                             
              location ~ .*\.php?$
              {
                   include conf/fcgi.conf;      
                   fastcgi_pass  127.0.0.1:10080;
                   fastcgi_index index.php;
              }

              log_format  access  '$remote_addr - $remote_user [$time_local] "$request" '
                                    '$status $body_bytes_sent "$http_referer" '
                                    '"$http_user_agent" $http_x_forwarded_for';
              access_log  /data1/logs/access.log  access;
      }

      server
      {
              listen  80;
              server_name  status.blog.s135.com;

              location / {
                   stub_status on;
                   access_log   off;
              }
      }
}

  ②、在/usr/local/webserver/nginx/conf/目录中创建fcgi.conf文件:
 

vi /usr/local/webserver/nginx/conf/fcgi.conf

  输入以下内容:
 

引用
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;

fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;

fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;

fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;

# PHP only, required if PHP was built with --enable-force-cgi-redirect
#fastcgi_param  REDIRECT_STATUS    200;

  5、启动Nginx
 

ulimit -SHn 51200
/usr/local/webserver/nginx/sbin/nginx -c /usr/local/webserver/nginx/conf/nginx.conf

 


  四、配置开机自动启动Nginx + PHP
 

vi /etc/rc.local

  在末尾增加以下内容:
 

引用
ulimit -SHn 51200
/usr/local/webserver/php/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 64 -u www -f /usr/local/webserver/php/bin/php-cgi
/usr/local/webserver/nginx/sbin/nginx -c /usr/local/webserver/nginx/conf/nginx.conf

 


  五、优化Linux内核参数
 

vi /etc/sysctl.conf

  在末尾增加以下内容:
 

引用
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 5000    65000

  使配置立即生效:
 

/sbin/sysctl -p

 


  六、在不停止Nginx服务的情况下平滑变更Nginx配置
  (1)、修改/usr/local/webserver/nginx/conf/nginx.conf配置文件后,请执行以下命令检查配置文件是否正确:
 

/usr/local/webserver/nginx/sbin/nginx -t

  如果屏幕显示以下两行信息,说明配置文件正确:
  the configuration file /usr/local/webserver/nginx/conf/nginx.conf syntax is ok
  the configuration file /usr/local/webserver/nginx/conf/nginx.conf was tested successfully

  (2)、这时,输入以下命令查看Nginx主进程号:
 

ps -ef | grep "nginx: master process" | grep -v "grep" | awk -F ' ' '{print $2}'

  屏幕显示的即为Nginx主进程号,例如:
  6302

  这时,执行以下命令即可使修改过的Nginx配置文件生效:
 

kill -HUP 6302

 

发表在 web server | 标签为 , | Nginx 0.5.33 + PHP 5.2.5 (FastCGI) 可以承受3万以上的并发连接数,相当于同等环境下Apache的10倍已关闭评论

Nginx PHP FastCGI 安装配置记录

因需要兼容老程序,这里用的还是 PHP4 ,可根据自己的需要更改编译选项。
tar jxvf php-4.4.8.tar.bz2
cd php-4.4.8
./configure \
--prefix=/usr/local/php-fcgi \
--enable-fastcgi \
--enable-discard-path \
--enable-force-cgi-redirect \
--enable-mbstring=all \
--enable-memcache \
--with-config-file-path=/usr/local/php-fcgi/etc \
--with-gd=/usr/local/gd \
--with-zlib \
--with-png \
--with-jpeg \
--with-freetype \
--with-mysql=/usr/local/mysql \
--with-dom
make
make install
cp -f php.ini-dist /usr/local/php-fcgi/etc/php.ini

安装 ZendOptimizer
Zend 的优化器,免费使用,如果加密了 PHP 程序文件,这是必须的。
如果没有使用 Zend 优化器,PHP 进程的内存会难以释放。
下载:http://www.zend.com/en/products/guard/downloads
tar zxvf ZendOptimizer-3.3.3-linux-glibc23-i386.tar.gz
cd ZendOptimizer-3.3.3-linux-glibc23-i386
./install
cd ..

安装 eAccelerator
PHP scripts 的缓存,对于提高 PHP 程序执行速度很有帮助。
下载:http://eaccelerator.net/
tar jxvf eaccelerator-0.9.5.2.tar.bz2
cd eaccelerator-0.9.5.2
/usr/local/php-fcgi/bin/phpize
./configure --enable-eaccelerator=shared --with-php-config=/usr/local/php-fcgi/bin/php-config
make
make install
cd ..

安装 memcache
用于缓存 sql 查询,对于降低数据库压力,提升查询速度有很大好处。
下载:http://pecl.php.net/package/memcache
tar zxvf memcache-2.2.3.tgz
cd memcache-2.2.3
/usr/local/php-fcgi/bin/phpize
./configure --with-php-config=/usr/local/php-fcgi/bin/php-config
make
make install

安装 Linghttpd's spawn-fcgi
用 Lighttpd 的 spawn-fcgi 来管理 PHP FastCGI 进程。
下载 Lighttpd: http://www.lighttpd.net/download
yum -y install pcre-devel
(debian: apt-get -y install libpcre3-dev)
tar zxvf lighttpd-1.4.19.tar.bz2
cd lighttpd-1.4.19
./configure --without-bzip2
make
cp -a src/spawn-fcgi /usr/local/php-fcgi/bin/
 

安装 Nginx
下载:http://nginx.net/
tar zxvf nginx-0.5.35.tar.gz
cd nginx-0.5.35
./configure \
--user=nobody \
--group=nobody \
--prefix=/usr/local/nginx \
--with-http_stub_status_module
make
make install

配置 PHP
vi /usr/local/php-fcgi/etc/php.ini
# 最大执行时间
max_execution_time = 5
# 打开全局变量兼容老程序
register_globals = On
# 默认编码
default_charset = "gbk"
# 扩展模块的目录
extension_dir = "/usr/local/php-fcgi/lib/php/extensions/no-debug-non-zts-20020429"
# 关闭 mysql 持久连接。高访问量下会把数据库可用连接用完。
mysql.allow_persistent = Off
# 降低连接超时时间
mysql.connect_timeout = 10
# session 文件存储目录,这里为两级目录,需要手动创建。
session.save_path = "2;/tmpfs/phpsession"
# session 过期时间设为一小时。
session.gc_maxlifetime = 3600
# 关闭
session.bug_compat_42 = 0
session.bug_compat_warn = 0

# 开启 eAccelerator
[eAccelerator]
extension="eaccelerator.so"
# 可使用内存设为了 32M,太大会启动不了 PHP。
eaccelerator.shm_size="32"
eaccelerator.cache_dir="/tmpfs/eaccelerator"
eaccelerator.enable="1"
eaccelerator.optimizer="1"
eaccelerator.check_mtime="1"
eaccelerator.debug="0"
eaccelerator.filter=""
eaccelerator.shm_max="0"
eaccelerator.shm_ttl="0"
eaccelerator.shm_prune_period="0"
eaccelerator.shm_only="0"
eaccelerator.compress="1"
eaccelerator.compress_level="9"

# 在 eAccelerator 之后启用 ZO ,避免 eaccelerator.so 不能加载。
[Zend]
zend_optimizer.optimization_level=1023
zend_extension_manager.optimizer=/usr/local/Zend/lib/Optimizer-3.3.3
zend_optimizer.version=3.3.3
zend_extension=/usr/local/Zend/lib/ZendExtensionManager.so

# 开启 memcache
[memcache]
extension=memcache.so

配置 Nginx
建立相应目录
mkdir /var/log/nginx
cd /usr/local/nginx
mv logs conf/vhosts
cd conf
vi nginx.conf

  1. # 运行 Nginx 的用户
  2. user  nobody nobody;
  3. # Nginx 的进程数
  4. worker_processes  8;
  5.  
  6. # 错误日志
  7. error_log  /var/log/nginx/error.log;
  8.  
  9. # pid 文件
  10. pid        /var/run/nginx.pid;
  11.  
  12. events {
  13. # 使用 epoll(For Linux Kernel 2.6+) 提升 Nginx 性能。
  14.     use  epoll;
  15. # 最大连接数
  16.     worker_connections  4096;
  17. }
  18.  
  19.  
  20. http {
  21. # 包含 mime types 的配置文件
  22.     include       conf/mime.types;
  23. # 默认类型
  24.     default_type  application/octet-stream;
  25.  
  26. # 定义 temp 的路径
  27.     client_body_temp_path  /tmpfs/nginx/client_body_temp;
  28.     proxy_temp_path        /tmpfs/nginx/proxy_temp;
  29.     fastcgi_temp_path      /tmpfs/nginx/fastcgi_temp;
  30.  
  31. # 如果 server_name 定义的域名过多,需要增大这个值
  32.     server_names_hash_bucket_size  128;
  33.  
  34. # 定义主访问日志格式,因开启了 gzip,加入了 $gzip_ratio
  35.     log_format  main  '$remote_addr - $remote_user [$time_local] $request '
  36.                       '"$status" $body_bytes_sent "$http_referer" '
  37.                       '"$http_user_agent" "$gzip_ratio"';
  38.  
  39. # 默认的访问日志存放文件
  40.     access_log  /var/log/nginx/access.log  main;
  41.  
  42. # Linux Kernel 2.4+ 可通过调用内核级 sendfile() 来提高性能
  43.     sendfile  on;
  44.  
  45. # FreeBSD 或基于 TCP_CORK 的 Linux 系统可使用
  46.     tcp_nopush on;
  47.  
  48. # 只在 keep-alive 连接状态中使用
  49.     tcp_nodelay  on;
  50.  
  51. # 设置保持连接超时时间 和 header 超时时间(单位:秒)
  52.     keepalive_timeout  60 15;
  53.  
  54. # 开启 gzip
  55.     gzip  on;
  56. # 压缩级别 1-9,9 为最高压缩级别
  57.     gzip_comp_level  9;
  58. # 回送给客户端最小的 gzip 压缩大小
  59.     gzip_min_length  1100;
  60. # 设置 gzip 缓存的大小,默认是 4-8k 之间
  61.     gzip_buffers  4 8k;
  62. # gzip http 版本
  63.     gzip_http_version  1.1;
  64. # 需要使用 gzip 压缩的文件类型
  65.     gzip_types  text/plain text/html text/css application/x-javascript text/xml application/xml application/xml+rss text/javascript;
  66.  
  67. # 定义默认主机
  68.     server {
  69. # 监听端口
  70.         listen       80;
  71. # 匹配所有域名
  72.         server_name  _ *;
  73. # 默认首页
  74.         index  index.php;
  75. # 根目录路径
  76.         root  /home/www;
  77. # 执行 php 程序文件的设置
  78.         location ~ .*\.php?$ {
  79.             include  conf/fcgi.conf;
  80.         }
  81. # 对于以下文件不记录访问日志
  82.         location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
  83.             access_log  off;
  84.         }
  85.     }
  86.  
  87. # 包含其它虚拟主机的配置
  88.     include  conf/vhosts/*.conf;
  89. }

vi fcgi.conf

  1. fastcgi_pass  127.0.0.1:10080;
  2.  
  3. fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
  4. fastcgi_param  SERVER_SOFTWARE    nginx;
  5.  
  6. fastcgi_param  QUERY_STRING       $query_string;
  7. fastcgi_param  REQUEST_METHOD     $request_method;
  8. fastcgi_param  CONTENT_TYPE       $content_type;
  9. fastcgi_param  CONTENT_LENGTH     $content_length;
  10.  
  11. fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
  12. fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
  13. fastcgi_param  REQUEST_URI        $request_uri;
  14. fastcgi_param  DOCUMENT_URI       $document_uri;
  15. fastcgi_param  DOCUMENT_ROOT      $document_root;
  16. fastcgi_param  SERVER_PROTOCOL    $server_protocol;
  17.  
  18. fastcgi_param  REMOTE_ADDR        $remote_addr;
  19. fastcgi_param  REMOTE_PORT        $remote_port;
  20. fastcgi_param  SERVER_ADDR        $server_addr;
  21. fastcgi_param  SERVER_PORT        $server_port;
  22. fastcgi_param  SERVER_NAME        $server_name;
  23.  
  24. # PHP only, required if PHP was built with --enable-force-cgi-redirect
  25. fastcgi_param  REDIRECT_STATUS    200;

再来配置 Discuz! 论坛和 SupeSite/X-Space 的虚拟主机
vi vhosts/main.conf

  1. server {
  2.     listen       80;
  3. # 分论坛可使用子域名
  4.     server_name  bbs.domain.com *.bbs.domain.com;
  5.     index  index.php;
  6.     root  /home/www/bbs;
  7. # 和 Apache Rewrite 规则很相似
  8.     rewrite  ^/archiver/((fid|tid)-[\w\-]+\.html)$ /archiver/index.php?$1;
  9.     rewrite  ^/forum-([0-9]+)-([0-9]+)\.html$ /forumdisplay.php?fid=$1&page=$2;
  10.     rewrite  ^/thread-([0-9]+)-([0-9]+)-([0-9]+)\.html$ /viewthread.php?tid=$1&extra=page\%3D$3&page=$2;
  11.     rewrite  ^/space-(username|uid)-(.+)\.html$ /space.php?action=viewpro&$1=$2;
  12.     rewrite  ^/tag-(.+)\.html$ /tag.php?name=$1;
  13.         location ~ .*\.php?$ {
  14.             include  conf/fcgi.conf;
  15.         }
  16.         location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
  17.             access_log  off;
  18.         }
  19.     }
  20.  
  21.     server {
  22.     listen       80;
  23.     server_name  blog.domain.com;
  24.     index  index.php;
  25.     root  /home/www/blog;
  26.     rewrite  ^([0-9]+)/spacelist(.*)$ index.php?$1/action_spacelist$2;
  27.     rewrite  ^([0-9]+)/viewspace_(.+)$ index.php?$1/action_viewspace_itemid_$2;
  28.     rewrite  ^([0-9]+)/viewbbs_(.+)$ index.php?$1/action_viewbbs_tid_$2;
  29.     rewrite  ^([0-9]+)/(.*)$ index.php?$1/$2;
  30.     rewrite  ^([0-9]+)$ index.php?$1;
  31.     rewrite  ^action_(.+)$ index.php?action_$1;
  32.     rewrite  ^category_(.+)$ index.php?action_category_catid_$1;
  33.     rewrite  ^itemlist_(.+)$ index.php?action_itemlist_catid_$1;
  34.     rewrite  ^viewnews_(.+)$ index.php?action_viewnews_itemid_$1;
  35.     rewrite  ^viewthread_(.+)$ index.php?action_viewthread_tid_$1;
  36.     rewrite  ^index([\.a-zA-Z0-9]*)$ index.php;
  37.     rewrite  ^html/([0-9]+)/viewnews_itemid_([0-9]+)\.html$ index.php?action_viewnews_itemid_$2;
  38.  
  39.     rewrite  ^/([0-9]+)/spacelist(.+)$ /index.php?uid/$1/action/spacelist/type$2;
  40.     rewrite  ^/([0-9]+)/viewspace(.+)$ /index.php?uid/$1/action/viewspace/itemid$2;
  41.     rewrite  ^/([0-9]+)/viewbbs(.+)$ /index.php?uid/$1/action/viewbbs/tid$2;
  42.     rewrite  ^/([0-9]+)/(.*)$ /index.php?uid/$1/$2;
  43.     rewrite  ^/([0-9]+)$ /index.php?uid/$1;
  44.  
  45.     rewrite  ^/action(.+)$ /index.php?action$1;
  46.     rewrite  ^/category(.+)$ /index.php?action/category/catid$1;
  47.     rewrite  ^/viewnews(.+)$ /index.php?action/viewnews/itemid$1;
  48.     rewrite  ^/viewthread(.+)$ /index.php?action/viewthread/tid$1;
  49.     rewrite  ^/mygroup(.+)$ /index.php?action/mygroup/gid$1;
  50. # 归档目录的默认首页设置
  51.         location /archiver/ {
  52.             index index.html;
  53.         }
  54.         location ~ .*\.php?$ {
  55.             include  conf/fcgi.conf;
  56.         }
  57.         location ~* ^.+.(jpg|jpeg|gif|css|png|js|ico)$ {
  58.             access_log  off;
  59.         }
  60.     }

用 tmpfs 提升性能
mkdir /tmpfs
在 /etc/fstab 中加入
tmpfs /tmpfs tmpfs size=256m,mode=1777 0 0

mount -a

创建相关目录
vi /usr/local/sbin/mkdir.sh

#/
bin
/
sh

 

mkdir
/
tmpfs
/
nginx


chown
-
R

nobody
:
nobody
/
tmpfs
/
nginx


chmod
-
R

1777
/
tmpfs
/
nginx

 

mkdir
/
tmpfs
/
eaccelerator


chown
-
R

nobody
:
nobody
/
tmpfs
/
eaccelerator


chmod
-
R

1777
/
tmpfs
/
eaccelerator

 

I
=
"
0 1 2 3 4 5 6 7 8 9 a b c d e f
"


for

acm

in
$
I
;

do


for

x

in
$
I
;

do


mkdir
-
p
/
tmpfs
/
phpsession
/$
acm
/$
x
;

done
;

done


chown
-
R

nobody
:
nobody
/
tmpfs
/
phpsession


chmod
-
R

1777
/
tmpfs
/
phpsession

chmod +x /usr/local/sbin/mkdir.sh
mkdir.sh

启动 PHP 和 Nginx
/usr/local/php-fcgi/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 32 -u nobody -g nobody -f /usr/local/php-fcgi/bin/php
监听在 127.0.0.1 的 10080 端口并开启 32 个进程,使用和 Nginx 一样的 nobody 用户。(PHP5 的执行程序是 php-cgi)
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
重启 PHP 进程可以先 killall php 再启动。
重启 Nginx
kill -HUP `cat /var/run/nginx.pid`

清除超过一小时没有被访问到的 eAccelerator 缓存文件和创建时间超过一小时的 php session 文件,防止占满空间。
vi /etc/crontab
0 * * * * root find /tmpfs/eaccelerator -type f -amin +60 -exec rm {} \;
0 * * * * root find /tmpfs/phpsession -type f -cmin +60 -exec rm {} \;

配置开机自启动
vi /etc/rc.local
/usr/local/sbin/mkdir.sh
/usr/local/php-fcgi/bin/spawn-fcgi -a 127.0.0.1 -p 10080 -C 32 -u nobody -g nobody -f /usr/local/php-fcgi/bin/php
/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf

方便重启 Nginx
vi ~/.bashrc
alias nginx='kill -HUP `cat /var/run/nginx.pid`'

source ~/.bashrc

 

----------------------------------------------------------------------------------------

Nginx
是俄罗斯人编写的十分轻量级的HTTP服务器,以事件驱动的方式编写,所以有非常好的性能,同时也是一个非常高效的反向代理、负载平衡。其拥有匹配Lighttpd的性能,同时还没有Lighttpd的内存泄漏问题,而且Lighttpd的mod_proxy也有一些问题并且很久没有更新。

因此我打算用其替代Apache应用于Linux
服务器上。但是Nginx并不支持cgi方式运行,原因是可以减少因此带来的一些程序上的漏洞。那么我们必须使用FastCGI方式来执行PHP程序。

下面是我成功地配置Nginx + PHP5 FastCGI的过程

 

首先安装或编译Nginx。

安装Nginx

源码包可以在官方主页
上下载。Ubuntu 7.10可以直接通过apt安装,也可以从这里下载
最新的deb包:

sudo apt-get install nginx

如果要自己编译的话,需要确保自己已经有编译器和PCRE的库(用于Nginx的rewrite模块,如果不需要这个模块可以在configure时使用./configure –without-rewrite)。编译方法如下:

wget http://sysoev.ru/nginx/nginx-0.5.34.tar.gz
tar zxvf nginx-0.5.34.tar.gz
cd nginx-0.5.34
./configure #默认配置安装路径为/usr/local/nginx 可以追加--prefix=/usr设置到/usr
make && make install  # install要求有root权限

Ubuntu安装之后的文件结构大致为:

  • 所有的配置文件都在/etc/nginx下,并且每个虚拟主机已经安排在了/etc/nginx/sites-available下
  • 程序文件在/usr/sbin/nginx
  • 日志放在了/var/log/nginx中
  • 并已经在/etc/init.d/下创建了启动脚本nginx
  • 默认的虚拟主机的目录设置在了/var/www/nginx-default

而自己利用默认配置编译的,则放在/usr/local/nginx下,以下是目录结构:

  • /usr/local/nginx/conf 配置目录
  • /usr/local/nginx/html 默认的网站根目录
  • /usr/local/nginx/logs 日志和pid文件目录
  • /usr/local/nginx/sbin 执行文件目录

下面可以启动nginx来看看效果(请确保80端口没有其他服务在使用):
Ubuntu请运行:

sudo /etc/init.d/nginx start

其他请运行:

/usr/local/nginx/sbin/nginx

然后就可以通过http://localhost/来看看效果了。

要配置nginx的自动运行,可以将/usr/local/nginx/sbin/nginx添加到/etc/rc.local中,Ubuntu可以执行

update-rc.d nginx defaults

安装PHP5

至于如何在Linux
上安装PHP,有很多文章,甚至很多平台上都有现成的软件包,无需自己编译。在这里我们需要的是cgi方式的php。Ubuntu下可以直接运行:

sudo apt-get install php-cgi

并且可以根据自己的情况安装一些字节码优化和缓存的扩展,如eaccelerator、apc、xcache等。

PHP5的CGI方式的一大优势是内置了FastCGI的支持,只需指明绑定的地址和端口参数便可以以FastCGI的方式运行,如下:

php-cgi -b 127.0.0.1:9000

如何配置其与nginx一起运行呢?

配置Nginx的PHP FastCGI

请将以下内容保存为fastcgi_params文件,保存于/usr/local/nginx/conf下(Ubuntu可保存于/etc/nginx下),他为我们的FastCGI模块设置了基本的环境变量:

#fastcgi_params
fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
fastcgi_param  SERVER_SOFTWARE    nginx;
fastcgi_param  QUERY_STRING       $query_string;
fastcgi_param  REQUEST_METHOD     $request_method;
fastcgi_param  CONTENT_TYPE       $content_type;
fastcgi_param  CONTENT_LENGTH     $content_length;
fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
fastcgi_param  REQUEST_URI        $request_uri;
fastcgi_param  DOCUMENT_URI       $document_uri;
fastcgi_param  DOCUMENT_ROOT      $document_root;
fastcgi_param  SERVER_PROTOCOL    $server_protocol;
fastcgi_param  REMOTE_ADDR        $remote_addr;
fastcgi_param  REMOTE_PORT        $remote_port;
fastcgi_param  SERVER_ADDR        $server_addr;
fastcgi_param  SERVER_PORT        $server_port;
fastcgi_param  SERVER_NAME        $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
fastcgi_param  REDIRECT_STATUS    200;

请特别注意加粗的一行,PHP-CGI特别需要此行信息来确定PHP文件的位置。

另外需要在PHP-CGI的配置文件(Ubuntu 上此配置文件位于/etc/php5/cgi/php.ini)中,打开cgi.fix_pathinfo选项:

cgi.fix_pathinfo=1;

这样php-cgi方能正常使用SCRIPT_FILENAME这个变量。

接下来在nginx的配置中针对php文件配置其利用FastCGI进程来执行:

server {
    index index.php;
    root  /usr/local/nginx/html;

    location ~ .*.php$ {
        include /usr/local/nginx/conf/fastcgi_params;  #请根据自己保存的路径进行设置
        fastcgi_index index.php;
        fastcgi_pass  127.0.0.1:9000; #请根据自己的FastCGI绑定的地址和端口进行配置
    }
}

通知Nginx重新载入配置:

kill -HUP `cat /usr/local/nginx/logs/nginx.pid`

Ubuntu用户可以使用init脚本:sudo /etc/init.d/nginx reload

然后启动php-cgi -b 127.0.0.1:9000

假设你在文档根目录放了index.php,并包含“”的内容,现在再看http://localhost/index.php便应该能看到php的调试信息了。

配置php进程

直接使用php-cgi的FastCGI运行方式有两个问题(貌似应该有解决方案,如果知道的话可以教教我):

  1. 如果进程崩溃,难以配置重新启动
  2. 单进程的效率低

因此,我们可以利用Lighttpd的spawn-fcgi来控制进程的运行。获得spawn-fcgi的方法如下:

wget http://www.lighttpd.net/download/lighttpd-1.4.18.tar.bz2 #获取Lighttpd的源码包
tar -xvjf lighttpd-1.4.18.tar.bz2
cd lighttpd-1.4.18
./configure  #编译
make
cp src/spawn-fcgi /usr/local/bin/spawn-fcgi #取出spawn-fcgi的程序

下面我们就可以使用 spawn-fcgi 来控制php-cgi的FastCGI进程了

/usr/local/bin/spawn-fcgi -a 127.0.0.1 -p 9000 -C 5 -u www-data -g www-data -f /usr/bin/php-cgi

参数含义如下

  • -f <fcgiapp> 指定调用FastCGI的进程的执行程序位置,根据系统上所装的PHP的情况具体设置
  • -a <addr> 绑定到地址addr
  • -p <port> 绑定到端口port
  • -s <path> 绑定到unix socket的路径path
  • -C <childs> 指定产生的FastCGI的进程数,默认为5(仅用于PHP)
  • -P <path> 指定产生的进程的PID文件路径
  • -u和-g FastCGI使用什么身份(-u 用户 -g 用户组)运行,Ubuntu下可以使用www-data,其他的根据情况配置,如nobody、apache等

然后我们可以将这行代码加入到/etc/rc.local文件底部,这样系统启动的时候也可以同时启动PHP的FastCGI进程

发表在 web server | 标签为 , , | Nginx PHP FastCGI 安装配置记录已关闭评论

Nginx+PHP+MySQL双机互备、全自动切换方案

在生产应用中,某台“Nginx+PHP+MySQL”接口数据服务器,扮演的角色十分重要,如果服务器硬件或Nginx、MySQL发生故障,而短时间内无法恢复,后果将非常严重。为了避免单点故障,我设计了此套方案,编写了failover.sh脚本,实现了双机互备、全自动切换,故障转移时间只需几十秒。

  一、双机互备、全自动切换方案:
  1、拓扑图:

点击查看原图

2、解释:
  (1)、假设外网域名blog.s135.com解析到外网虚拟IP 72.249.146.214上,内网hosts设置db10对应内网虚拟IP 192.168.146.214

  (2)、默认情况下,由主机绑定内、外网虚拟IP,备机作为备份,当主机的MySQL、Nginx或服务器出现故障无法访问时,备机会自动接管内、外网虚拟IP。两台服务器都启动负责监控、自动切换虚拟IP的守护进程/usr/bin/nohup /bin/sh /usr/local/webserver/failover/failover.sh 2>&1 > /dev/null &

  (3)、主机和备机上的MySQL服务器互为主从,互相同步。在主机处于活动状态(即由主机绑定虚拟IP)时,读写主机的MySQL,写到主机的数据会同步到备机;在备机处于活动状态时,读写备机的MySQL,写到备机的数据会同步到主机(如果主机上的MySQL死掉暂时无法同步,主机上的MySQL恢复后,数据会自动从备机上同步过来,反之亦然)。

  (4)、主机处于活动状态时,每20秒会把/data0/htdocs/(网页、程序、图片存放目录)、/usr/local/webserver/php/etc/(php.ini等配置文件目录)、/usr/local/webserver/nginx/conf/(Nginx配置文件目录)三个目录下的文件通过rsync推送到备机服务器上的对应目录(增量推送,两台服务器上一样的文件不会重复推送),反之如果备机处于活动状态时,每20秒会尝试把文件推送到主机。rsync的配置文件见两台服务器的/etc/rsyncd.conf,rsync守护进程的启动命令为rsync --daemon

  3、自动切换流程
  (1)、主机默认绑定内、外网虚拟IP,当主机的MySQL、Nginx无法访问或服务器宕机,主机上的failover.sh守护进程会自动摘除自己绑定的内、外网虚拟IP(如果主机上的failover.sh死掉,无法摘除自己绑定的虚拟IP也没关系),备机上的failover.sh守护进程会自动接管备机原来绑定的内、外网虚拟IP,并发送ARPing包给内、外网网关更新MAC,强行接管。

  (2)、备机绑定虚拟IP后,会发送ARPing包给内、外网网关,通知网关更新虚拟IP的MAC地址为备机的MAC地址,从而保证了切换后能够通过虚拟IP及时访问到备机。

  (3)、如果主机的MySQL、Nginx启动起来,全部恢复正常访问,主机上的failover.sh守护进程会检测主机上的MySQL数据是否已经完全从备机上同步过来。如果同步延迟时间为0,主机会自动接管内、外网虚拟IP,并发送ARPing包给内、外网网关,而备机也会自动摘除内、外网虚拟IP。

  (4)、整个切换流程均由failover.sh自动完成,无需人工处理。 

  4、注意事项(很重要):
  (1)、crontab里的文件没有做自动同步,如果修改,需要手工在两台服务器上都做修改。

  (2)、/data0/htdocs/目录内任何用ln -s建立的软连接,rsync不会自动同步,如果在一台服务器上建了软连接,需要手工在另外一台服务器上也建相同的软连接。

  (3)、如果要删除/data0/htdocs/目录内的某些文件或目录,需要先删除处于活动状态(即绑定了虚拟IP)服务器上的文件或目录,再删除处于备用状态服务器上的文件或目录。

  (4)、除了/data0/htdocs/(网页、程序、图片存放目录)、/usr/local/webserver/php/etc/(php.ini等配置文件目录)、/usr/local/webserver/nginx/conf/(Nginx配置文件目录)三个目录之外的其他配置修改,需要在两台服务器上都做修改。

二、配置文档与脚本:
  1、主机、备机两台服务器的rsync配置(配置相同)
  (1)、rsync配置文件
 

vi /etc/rsyncd.conf

  输入一些内容并保存:
 

引用
uid = root
gid = root
use chroot = no
max connections = 20
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log

[data0_htdocs]
path = /data0/htdocs/
ignore errors
read only = no
hosts allow = 192.168.146.0/24
hosts deny = 0.0.0.0/32

[php_etc]
path = /usr/local/webserver/php/etc/
ignore errors
read only = no
hosts allow = 192.168.146.0/24
hosts deny = 0.0.0.0/32

[nginx_conf]
path = /usr/local/webserver/nginx/conf/
ignore errors
read only = no
hosts allow = 192.168.146.0/24
hosts deny = 0.0.0.0/32

  (2)、启动rsync守护进程
 

/usr/bin/rsync --daemon

  2、两台MySQL互为主从的配置
  这里就不详细写出互为主从的配置过程了,如果不懂的朋友可以在Google上搜一下。有一点需要指出,my.cnf配置文件中请加上skip-name-resolve参数,使用IP来进行MySQL帐号验证。

  3、主机、备机两台服务器负载监控、虚拟IP自动切换的failover.sh守护进程
  (1)、启动failover.sh守护进程(为了开机能够自动运行,请将以下语句添加到/etc/rc.local文件中):
 

/usr/bin/nohup /bin/sh /usr/local/webserver/failover/failover.sh 2>&1 > /dev/null &

  (2)、停止failover.sh守护进程:
 

ps -ef | grep failover.sh

  会显示以下信息:
  root     15428     1  0 Nov17 ?        00:00:03 /bin/sh /usr/local/webserver/failover/failover.sh
  root     20123  6878  0 16:16 pts/2    00:00:00 grep failover.sh


  然后杀死failover.sh的进程:
 

kill -9 15428

  (3)、failover.sh代码内容(请注意其中的type设置,主机设为master,备机设为slave
):
 

#!/bin/sh
LANG=C
date=$(date -d "today" +"%Y-%m-%d %H:%M:%S")

#---------------配置信息(开始)---------------
#类型:主机设为master,备机设为slave
type="master"

#主机、备机切换日志路径
logfile="/var/log/failover.log"

#MySQL可执行文件地址,例如/usr/local/mysql/bin/mysql;MySQL用户名;密码;端口
mysql_bin="/usr/local/webserver/mysql/bin/mysql"
mysql_username="root"
mysql_password="123456"
mysql_port="3306"

#内网网关
gateway_eth0="192.168.146.1"

#主机内网真实IP
rip_eth0_master="192.168.146.213"

#备机内网真实IP
rip_eth0_slave="192.168.146.215"

#主机、备机内网共用的虚拟IP
vip_eth0_share="192.168.113.214"

#外网网关
gateway_eth1="72.249.146.193"

#主机外网真实IP
rip_eth1_master="72.249.146.213"

#备机外网真实IP
rip_eth1_slave="72.249.146.215"

#主机、备机外网共用的虚拟IP
vip_eth1_share="72.249.146.214"
#---------------配置信息(结束)---------------

#绑定内、外网虚拟IP
function_bind_vip()
{
   /sbin/ifconfig eth0:vip ${vip_eth0_share} broadcast ${vip_eth0_share} netmask 255.255.255.255 up
   /sbin/route add -host ${vip_eth0_share} dev eth0:vip
   /sbin/ifconfig eth1:vip ${vip_eth1_share} broadcast ${vip_eth1_share} netmask 255.255.255.255 up
   /sbin/route add -host ${vip_eth1_share} dev eth1:vip
   /usr/local/webserver/php/sbin/php-fpm reload
   kill -USR1 `cat /usr/local/webserver/nginx/logs/nginx.pid`
   /sbin/service crond start
}

#解除内、外网虚拟IP
function_remove_vip()
{
   /sbin/ifconfig eth0:vip ${vip_eth0_share} broadcast ${vip_eth0_share} netmask 255.255.255.255 down
   /sbin/ifconfig eth1:vip ${vip_eth1_share} broadcast ${vip_eth1_share} netmask 255.255.255.255 down
   /sbin/service crond stop
}

#主机向备机推送文件的函数
function_rsync_master_to_slave()
{
   /usr/bin/rsync -zrtuog /data0/htdocs/ ${rip_eth0_slave}::data0_htdocs/ > /dev/null 2>&1
   /usr/bin/rsync -zrtuog /usr/local/webserver/php/etc/ ${rip_eth0_slave}::php_etc/ > /dev/null 2>&1
   /usr/bin/rsync -zrtuog /usr/local/webserver/nginx/conf/ ${rip_eth0_slave}::nginx_conf/ > /dev/null 2>&1
}

#备机向主机推送文件的函数
function_rsync_slave_to_master()
{
   /usr/bin/rsync -zrtuog /data0/htdocs/ ${rip_eth0_master}::data0_htdocs/ > /dev/null 2>&1
   /usr/bin/rsync -zrtuog /usr/local/webserver/php/etc/ ${rip_eth0_master}::php_etc/ > /dev/null 2>&1
   /usr/bin/rsync -zrtuog /usr/local/webserver/nginx/conf/ ${rip_eth0_master}::nginx_conf/ > /dev/null 2>&1
}

#虚拟IP ARPing
function_vip_arping()
{
 /sbin/arping -I eth0 -c 3 -s ${vip_eth0_share} ${gateway_eth0} > /dev/null 2>&1
 /sbin/arping -I eth1 -c 3 -s ${vip_eth1_share} ${gateway_eth1} > /dev/null 2>&1  
}

while true
do
   #用HTTP协议检查虚拟IP
   if (curl -m 30 -G 
http://$
{vip_eth1_share}/ > /dev/null 2>&1) && (${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${vip_eth0_share}" -e"show slave status\G" > /dev/null 2>&1)
   then
   #取得与内网VIP绑定的服务器内网IP
   eth0_active_server=$(${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${vip_eth0_share}" -e"show slave status\G" | grep "Master_Host" | awk -F ': ' '{printf $2}')
   
   #如果内网VIP=主机内网IP(主机MySQL中的Master_Host显示的是备机的域名或IP),且本机为主机
   if [ "${eth0_active_server}" = "${rip_eth0_slave}" ] && [ "${type}" = "master" ]
   then
     function_rsync_master_to_slave
     function_vip_arping    
   #如果内网VIP=备机内网IP(备机MySQL中的Master_Host显示的是主机的域名或IP)
   elif [ "${eth0_active_server}" = "${rip_eth0_master}" ]
   then
     if (curl -m 30 -G 
http://$
{rip_eth1_master}/ > /dev/null 2>&1) && (${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${rip_eth0_master}" -e"show slave status\G" | grep "Seconds_Behind_Master: 0" > /dev/null 2>&1)
     then
       #如果主机能够访问,数据库同步无延迟,且本机就是主机,那么由本机绑定虚拟IP
       if [ "${type}" = "master" ]
       then
         #如果本机为主机
      function_bind_vip
         function_vip_arping
         echo "${date} 主机已绑定虚拟IP!(Type:1)" >> ${logfile}
       else
         #如果本机为备机
      function_remove_vip
         echo "${date} 备机已去除虚拟IP!(Type:2)" >> ${logfile}
       fi
     else
       if [ "${type}" = "slave" ]
       then
         #如果本机为备机
      function_rsync_slave_to_master        
         function_vip_arping
       fi      
     fi
   fi
   else
       #虚拟IP无法访问时,判断主机能否访问
       if (curl -m 30 -G 
http://$
{rip_eth1_master}/ > /dev/null 2>&1) && (${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${rip_eth0_master}" -e"show slave status\G" > /dev/null 2>&1)
       then
           #如果主机能够访问,且本机就是主机,那么由本机绑定虚拟IP
           if [ "${type}" = "master" ]
           then
               function_bind_vip
               function_vip_arping
               echo "${date} 主机已绑定虚拟IP!(Type:3)" >> ${logfile}
           else
               function_remove_vip
               echo "${date} 备机已去除虚拟IP!(Type:4)" >> ${logfile}
           fi
   elif (curl -m 30 -G 
http://$
{rip_eth1_slave}/ > /dev/null 2>&1) && (${mysql_bin} -u"${mysql_username}" -p"${mysql_password}" -P"${mysql_port}" -h"${rip_eth0_slave}" -e"show slave status\G" > /dev/null 2>&1)
       then
           #如果主机不能访问而备机能够访问,且本机就是备机,那么由备机绑定虚拟IP
           if [ "${type}" = "slave" ]
           then
               function_bind_vip
               function_vip_arping
               echo "${date} 备机已绑定虚拟IP!(Type:5)" >> ${logfile}
           else
               function_remove_vip
               echo "${date} 主机已去除虚拟IP!(Type:6)" >> ${logfile}
           fi
       else
           echo "${date} 主机、备机全部无法访问!(Type:7)" >> ${logfile}
       fi
   fi
   #每次循环暂停20秒(即间隔20秒检测一次)
   sleep 20
done

发表在 web server | 标签为 , | Nginx+PHP+MySQL双机互备、全自动切换方案已关闭评论

网易开通了一个开源软件的镜像站点

网易开通了一个开源软件的镜像站点,网址为:

  http://mirrors.163.com/

  提供的镜像有:

  1、Linux及BSD发行版镜像:FreeBSD、OpenBSD、RedHat、archlinux、centos、debian、fedora、gentoo、trixbox、ubuntu等。

  2、开源软件镜像:eclipse可扩展开发平台、防火墙、openfiler网络存储管理工具。

  该镜像目前只有一台杭州电信的服务器,网通用户访问可能会比较慢。

 


  如果您安装 CentOS 5.2 系统的服务器位于电信机房,您可以修改/etc/yum.repos.d/CentOS-Base.repo文件,将它的yum源更改成网易的镜像,代替国外的镜像,以便获取更快的下载速度。

  您可以按照以下步骤从 blog.s135.com

下载修改后的 CentOS-Base.repo 文件到您的服务器。

 

cd /etc/yum.repos.d/
mv CentOS-Base.repo CentOS-Base.repo.bak
wget http://blog.s135.com/soft/linux/centos/5.2/CentOS-Base.repo

 




  附:修改后的 CentOS-Base.repo 文件内容如下:

 

  1. # CentOS-Base.repo

  2. #

  3. # This file uses a new mirrorlist system developed by Lance Davis for CentOS.

  4. # The mirror system uses the connecting IP address of the client and the

  5. # update status of each mirror to pick mirrors that are updated to and

  6. # geographically close to the client.  You should use this for CentOS updates

  7. # unless you are manually picking other mirrors.

  8. #

  9. # If the mirrorlist= does not work for you, as a fall back you can try the 

  10. # remarked out baseurl= line instead.

  11. #

  12. #

      
  13.   
  14. [base]   
  15. name=CentOS-$releasever - Base
  16. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os

  17. #baseurl=http://mirror.centos.org/centos/$releasever/os/$basearch/

      
  18. baseurl=http:
    //mirrors.163.com/centos/$releasever/os/$basearch/

      
  19. gpgcheck=1   
  20. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
  21.  
  22. #released updates 

      
  23. [updates]   
  24. name=CentOS-$releasever - Updates
  25. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates

  26. #baseurl=http://mirror.centos.org/centos/$releasever/updates/$basearch/

      
  27. baseurl=http:
    //mirrors.163.com/centos/$releasever/updates/$basearch/

      
  28. gpgcheck=1   
  29. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
  30.  
  31. #packages used/produced in the build but not released

      
  32. [addons]   
  33. name=CentOS-$releasever - Addons
  34. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=addons

  35. #baseurl=http://mirror.centos.org/centos/$releasever/addons/$basearch/

      
  36. baseurl=http:
    //mirrors.163.com/centos/$releasever/addons/$basearch/

      
  37. gpgcheck=1   
  38. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
  39.  
  40. #additional packages that may be useful

      
  41. [extras]   
  42. name=CentOS-$releasever - Extras
  43. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras

  44. #baseurl=http://mirror.centos.org/centos/$releasever/extras/$basearch/

      
  45. baseurl=http:
    //mirrors.163.com/centos/$releasever/extras/$basearch/

      
  46. gpgcheck=1   
  47. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5
  48.  
  49. #additional packages that extend functionality of existing packages

      
  50. [centosplus]   
  51. name=CentOS-$releasever - Plus
  52. #mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus

  53. #baseurl=http://mirror.centos.org/centos/$releasever/centosplus/$basearch/

      
  54. baseurl=http:
    //mirrors.163.com/centos/$releasever/centosplus/$basearch/

      
  55. gpgcheck=1   
  56. enabled=0   
  57. gpgkey=http:
    //mirror.centos.org/centos/RPM-GPG-KEY-CentOS-5

      

发表在 info | 网易开通了一个开源软件的镜像站点已关闭评论

亿级数据的高并发通用搜索引擎架构设计

曾经在七月,写过一篇文章──《基于Sphinx+MySQL的千万级数据全文检索(搜索引擎)架构设计
》,前公司的分类信息搜索基于此架构,效果明显,甚至将很大一部分带Where条件的MySQL SQL查询,都改用了Sphinx+MySQL搜索。但是,这套架构仍存在局限:一是MySQL本身的并发能力有限,在200~300个并发连接下,查询和更新就比较慢了;二是由于MySQL表的主键与Sphinx索引的ID一一对应,从而无法跨多表建立整站查询,而且新增加类别还得修改配置文件,比较麻烦;三是因为和MySQL集成,无法发挥出Sphinx的优势。

  最近,我设计出了下列这套最新的搜索引擎架构,目前已经写出“搜索查询接口”和“索引更新接口”的beta版。经测试,在一台“奔腾四 3.6GHz 双核CPU、2GB内存”的普通PC机,7000万条索引记录的条件下,“搜索查询接口”平均查询速度为0.0XX秒(查询速度已经达到百度、谷歌、搜狗、中国雅虎等搜索引擎的水平,详见文章末尾的“附2”),并且能够支撑高达5000的并发连接;而“索引更新接口”进行数据分析、入队列、返回信息给用户的全过程,高达1500 Requests/Sec。

  “队列控制器”这一部分是核心,它要控制队列读取,更新MySQL主表与增量表,更新搜索引擎数据存储层Tokyo Tyrant,准实时(1分钟内)完成更新Sphinx增量索引,定期合并Sphinx索引。我预计在这周写出beta版。

点击查看原图

  图示说明:

  1、搜索查询接口:
  ①、Web应用服务器通过HTTP POST/GET方式,将搜索关键字等条件,传递给搜索引擎服务器的search.php接口;
  ②③、search.php通过Sphinx的API(我根据最新的Sphinx 0.9.9-rc1 API,改写了一个C语言的PHP扩展sphinx.so),查询Sphinx索引服务,取得满足查询条件的搜索引擎唯一ID(15位搜索唯一ID:前5位类别ID+后10位原数据表主键ID)列表;
  ④⑤、search.php将这些ID号作为key,通过Memcache协议一次性从Tokyo Tyrant中mget取回ID号对应的文本数据。
  ⑥⑦、search.php将搜索结果集,按查询条件,进行摘要和关键字高亮显示处理,以JSON格式或XML格式返回给Web应用服务器。

  2、索引更新接口:
  ⑴、Web应用服务器通过HTTP POST/GET方式,将要增加、删除、更新的内容告知搜索服务器的update.php接口;
  ⑵、update.php将接收到的信息处理后,写入TT高速队列(我基于Tokyo Tyrant做的一个队列系统);
  注:这两步的速度可达到1500次请求/秒以上,可应对6000万PV的搜索索引更新调用。

  3、搜索索引与数据存储控制:
  ㈠、“队列控制器”守护进程从TT高速队列中循环读取信息(每次50条,直到末尾);
  ㈡、“队列控制器”将读取出的信息写入搜索引擎数据存储层Tokyo Tyrant;
  ㈢、“队列控制器”将读取出的信息异步写入MySQL主表(这张主表按500万条记录进行分区,仅作为数据永久性备份用);
  ㈣、“队列控制器”将读取出的信息写入MySQL增量表;
  ㈤、“队列控制器”在1分钟内,触发Sphinx更新增量索引,Sphinx的indexer会将MySQL增量表作为数据源,建立增量索引。Sphinx的增量索引和作为数据源的MySQL增量表成对应关系;
  ㈥、“队列控制器”每间隔3小时,短暂停止从TT高速队列中读取信息,并触发Sphinx将增量索引合并入主索引(这个过程非常快),同时清空MySQL增量表(保证了MySQL增量表的记录数始终只有几千条至几十万条,大大加快Sphinx增量索引更新速度),然后恢复从TT高速队列中取出数据,写入MySQL增量表。

  本架构使用的开源软件:

  1、Sphinx 0.9.9-rc1
  2、Tokyo Tyrant 1.1.9
  3、MySQL 5.1.30
  4、Nginx 0.7.22
  5、PHP 5.2.6

  本架构自主研发的程序:

  1、搜索查询接口(search.php)
  2、索引更新接口(update.php)
  3、队列控制器
  4、Sphinx 0.9.9-rc1 API的PHP扩展(sphinx.so)
  5、基于Tokyo Tyrant的高速队列系统

 


  附1:MySQL FullText、Lucene搜索、Sphinx搜索的第三方对比结果:

  1、查询速度:
  MySQL FullText最慢,Lucene、Sphinx查询速度不相上下,Sphinx稍占优势。
  点击查看原图

  2、建索引速度:
  Sphinx建索引速度是最快的,比Lucene快9倍以上。因此,Sphinx非常适合做准实时搜索引擎。

  3、详细对比数据见以下PDF文档: 

     

发表在 article | 标签为 , | 亿级数据的高并发通用搜索引擎架构设计已关闭评论

易趣网淘宝网5年交战史

自2003年阿里巴巴旗下淘宝网上线以来,易趣网与淘宝网的战斗一直没有停止过。从一下淘宝网与易趣网的交战历史,可以看出在斗争中成长的两大C2C网站,也可以看到中国C2C发展的一丝脉络。
 

 

  易趣淘宝交战史:
 

 

  1999年8月 两位哈佛商学院毕业生,邵亦波和谭海音,在中国上海创办易趣网。成立之初,公司在上海一个两居室的民居内办公。两位创始人邵亦波和谭海英是当时仅有的两名员工。
 

 

  2000年7月 易趣推出个人网上开店服务,短短一周即吸引5,000多位网友“尝鲜”,此举切实地培养起中国首批真正靠网络来赚钱的网民。
 

 

  2001年7月 易趣宣布网站开始对卖家登录物品收取登录费。
 

 

  2002年9月 易趣开始对卖家网上商品成交后收取商品交易服务费。易趣开始进入了电子商务平台非免费运营的阶段,也标志着中国电子商务的发展的一个里程碑。
 

 

  2003年6月,eBay投资1.5亿美金,收购易趣(美国)公司的股份。易趣公司和eBay展开全面合作。
 

 

  2003年5月10日,淘宝网上线。同时宣布全站免费。
 

 

  2003年,电子商务巨头美国eBay在这个时候投资1.8亿美元,接管易趣,
 

 

  2003年,淘宝网上线。
 

 

  2003年,eBay将易趣网更名为eBay易趣。
 

 

  2003年10月,淘宝网发布了“支付宝”服务。
 

 

  2004年2月2日,易趣正式调低了自己的商品登录费用,这是易趣采取收费策略后第一次“降价让利”。
 

 

  2004年4月,yahoo与新浪合作的一拍网成立。
 

 

  2004年9月17日,易趣与eBay正式完成对接。
 

 

  2005年4月,淘宝网和搜狐宣布结成战略联盟,紧接着在5月,成为MSN中国拍卖频道的合作伙伴。
 

 

  2005年5月1日易趣网再次宣布登录费、月租费下调;6月9日的“安付通”升级。
 

 

  2005年7月11日,贝宝(PayPal China)中国网站正式开通,标志着贝宝正式登陆中国市场。
 

 

  2005年10月20日,淘宝网宣布将继续免费三年。
 

 

  2006年5月10日,正式推出全新B2C(企业对个人)业务——淘宝商城。并同时推出竞价排名服务“招财进宝”,在宣布继续免费3年之后,这项有偿增值服务被认为是“变相收费”,成为淘宝成立以来最大的一次改革。
 

 

  2006年12月,eBay与TOM在线合作携手组建一家合资公司,结合双方的优势资源,专为中国市场打造一个本地化的交易平台。TOM在线CEO王雷雷同时兼任合资公司CEO。
 

 

  2007年7月,eBay和TOM联手打造的全新交易平台—易趣正式上线启用。
 

 

  2008年4月,淘宝B2C平台正式上线。与此同时,淘宝将对该B2C的“品牌/商城”业务收费,此举被认为是提前收费,违反了淘宝2005年10月宣布的继续免费3年的承诺。同月,淘宝出现轰动一时的“评价门”事件。
 

 

  2008年4月14日,易趣针对老卖家、其他网站卖家和新手卖家发起一轮“易趣卖家共成长计划”,根据不同层面的卖家需求,提供从认证、培训到推广等各种免费且有效的资源支持,帮助这三类卖家在易趣上快速开店、稳步成长。凡是在易趣上开有店铺并提交了准确个人信息的卖家都可报名参加易趣这一成长计划。
 

 

  2008年5月5日,易趣宣布,用户到易趣上开店,易趣将终身免收包括高级店铺和超级店铺在内的店铺费,并免收商品登录费、店铺使用费等传统收费项目。这意味着,易趣这一国内首家收费的C2C网站,在经过若干年的收费探索后,开始转向全平台免费使用的模式。

发表在 info | 易趣网淘宝网5年交战史已关闭评论

C++ socket 编程

使用socket写代码主要是要看自己的需求是什么。
如果通信时,内容很重要就要使TCP方式。
如果用户数太多,可能就要使用UDP方式了。
在TCP模式下,最简单的方式就是这样的,使阻塞方式:
服务端:
1.初始化socket环境,创建socket
2.梆定一个端口
3.开始监听
4.接收客户端
5.接收到客户端之后,使用这个socket来与这个客户通信

#include "stdAfx.h"
#include <winsock2.h>
#include <mswsock.h>
#include <iostream>

using namespace std;

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")

DWORD IniSOCKDLL()
{
WORD wVersionRequested;
WSADATA wsaData;
int err=0;

wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
return err;
}

int main(int argc, char* argv[])
{
cout<<"程序开始"<<endl;
IniSOCKDLL();
SOCKET ss=WSASocket(AF_INET,
   SOCK_STREAM,
   0,
   NULL,
   0,
   NULL);

SOCKADDR_IN addr;
int len;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr = htonl(INADDR_ANY);
addr.sin_port = htons(1002);
len=sizeof(addr);

bind(ss , (PSOCKADDR)&addr , len);
listen(ss,5);

SOCKET sc=accept(ss,(PSOCKADDR)&addr,&len);
char buff[1024];
ZeroMemory(buff,1024);
recv(sc,buff,1024,0);
cout<<buff<<endl;

ZeroMemory(buff,1024);
memcpy(buff,"123",3);
send(sc,buff,3,0);

closesocket(sc);
closesocket(ss);
return 0;
}

客户端:
1.初始化socket环境,创建socket
2.连接服务端
3.开启一个线程来接收数据
4.使用send直接发数据包

#include "stdAfx.h"
#include <winsock2.h>
#include <mswsock.h>
#include <iostream>

using namespace std;

#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "mswsock.lib")

DWORD IniSOCKDLL()
{
WORD wVersionRequested;
WSADATA wsaData;
int err=0;

wVersionRequested = MAKEWORD( 2, 2 );
err = WSAStartup( wVersionRequested, &wsaData );
return err;
}

int main(int argc, char* argv[])
{
IniSOCKDLL();
SOCKET sc=WSASocket(AF_INET,
   SOCK_STREAM,
   0,
   NULL,
   0,
   NULL);

SOCKADDR_IN addr;
int len;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
addr.sin_port = htons(1002);
len=sizeof(addr);

connect(sc, (struct sockaddr *)&addr, len);

char buff[1024];
ZeroMemory(buff,1024);
memcpy(buff,"123",3);
send(sc,buff,3,0);

recv(sc,buff,1024,0);
cout<<buff<<endl;

closesocket(sc);
return 0;
}

由这个我们可以做一个这样的模型:
为每个阻塞函数开一个线程,让它来处理。
这就要留意退出的时候把这一些线程给关闭。

 

当然TCP方式的模型还有事件选择模型。
就是把所有的网络事件和我们的一个程序里定义的事件梆定。
这个有它的好处,可能可以让我们更好的写一个线程来管理
接收与发送。
现在来讲一下一个完成端口模型。

完成端口

一个完成端口其实就是一个通知队列,由操作系统把已经完成的重叠I/O请求的通知
放入其中。当某项I/O操作一旦完成,某个可以对该操作结果进行处理的工作者线程
就会收到一则通知。而套接字在被创建后,可以在任何时候与某个完成端口进行关
联。

步骤:
1、创建一个空的完成端口;
2、得到本地机器的CPU个数;
3、开启CPU*2个工作线程(又名线程池),全部都在等待完成端口的完成包;
4、创建TCP的监听socket,使用事件邦定,创建监听线程;
5、当有人连接进入的时候,将Client socket保存到一个我们自己定义的关键键,
    并把它与我们创建的完成端口关联;
6、使用WSARecv和WSASend函数投递一些请求,这是使用重叠I/O的方式;
7、重复5~6;

注:1、重叠I/O的方式中,接收与发送数据包的时候,一定要进行投递请求这是
    它们这个体系结构的特点
    当然,在完成端口方式中,不是直接使用的WSARecv和WSASend函数进行请求
    的投递的。而是使用的ReadFile,Write的方式
   2、完成端口使用了系统内部的一些模型,所以我们只要按照一定的顺序调用就
    可以完成了。
   3、完成端口是使用在这样的情况下,有成千上万的用户连接的时候,它能够
    保证性能不会降低。

#include <winsock2.h>
#include <windows.h>
#include <stdio.h>

#define PORT 5150
#define DATA_BUFSIZE 8192

//关键项
typedef struct
{
   OVERLAPPED Overlapped;
   WSABUF DataBuf;
   CHAR Buffer[DATA_BUFSIZE];
   DWORD BytesSEND;
   DWORD BytesRECV;
} PER_IO_OPERATION_DATA, * LPPER_IO_OPERATION_DATA;

typedef struct
{
   SOCKET Socket;
} PER_HANDLE_DATA, * LPPER_HANDLE_DATA;

DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID);

void main(void)
{
   SOCKADDR_IN InternetAddr;
   SOCKET Listen;
   SOCKET Accept;
   HANDLE CompletionPort;
   SYSTEM_INFO SystemInfo;
   LPPER_HANDLE_DATA PerHandleData;
   LPPER_IO_OPERATION_DATA PerIoData;
   int i;
   DWORD RecvBytes;
   DWORD Flags;
   DWORD ThreadID;
   WSADATA wsaData;
   DWORD Ret;

   if ((Ret = WSAStartup(0x0202, &wsaData)) != 0)
   {
      printf("WSAStartup failed with error %d\n", Ret);
      return;
   }

   //打开一个空的完成端口

   if ((CompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, 0, 0)) == NULL)
   {
      printf( "CreateIoCompletionPort failed with error: %d\n", GetLastError());
      return;
   }

   // Determine how many processors are on the system.

   GetSystemInfo(&SystemInfo);

   // 开启cpu个数的2倍个的线程

   for(i = 0; i < SystemInfo.dwNumberOfProcessors * 2; i++)
   {
      HANDLE ThreadHandle;

      // Create a server worker thread and pass the completion port to the thread.

      if ((ThreadHandle = CreateThread(NULL, 0, ServerWorkerThread, CompletionPort,
         0, &ThreadID)) == NULL)
      {
         printf("CreateThread() failed with error %d\n", GetLastError());
         return;
      }

      // Close the thread handle
      CloseHandle(ThreadHandle);
   }

   //打开一个服务器socket

   if ((Listen = WSASocket(AF_INET, SOCK_STREAM, 0, NULL, 0,
      WSA_FLAG_OVERLAPPED)) == INVALID_SOCKET)
   {
      printf("WSASocket() failed with error %d\n", WSAGetLastError());
      return;
   }

   InternetAddr.sin_family = AF_INET;
   InternetAddr.sin_addr.s_addr = htonl(INADDR_ANY);
   InternetAddr.sin_port = htons(PORT);

   if (bind(Listen, (PSOCKADDR) &InternetAddr, sizeof(InternetAddr)) == SOCKET_ERROR)
   {
      printf("bind() failed with error %d\n", WSAGetLastError());
      return;
   }

   if (listen(Listen, 5) == SOCKET_ERROR)
   {
      printf("listen() failed with error %d\n", WSAGetLastError());
      return;
   }

   //开始接收从客户端来的连接

   while(TRUE)
   {
      if ((Accept = WSAAccept(Listen, NULL, NULL, NULL, 0)) == SOCKET_ERROR)
      {
         printf("WSAAccept() failed with error %d\n", WSAGetLastError());
         return;
      }

      // 创建一个关键项用于保存这个客户端的信息,用户接收发送的重叠结构,
      // 还有使用到的缓冲区
      if ((PerHandleData = (LPPER_HANDLE_DATA) GlobalAlloc(GPTR,
         sizeof(PER_HANDLE_DATA))) == NULL)
      {
         printf("GlobalAlloc() failed with error %d\n", GetLastError());
         return;
      }

      // Associate the accepted socket with the original completion port.

      printf("Socket number %d connected\n", Accept);
      PerHandleData->Socket = Accept;

      //与我们的创建的那个完成端口关联起来,将关键项也与指定的一个完成端口关联
      if (CreateIoCompletionPort((HANDLE) Accept, CompletionPort, (DWORD) PerHandleData,
         0) == NULL)
      {
         printf("CreateIoCompletionPort failed with error %d\n", GetLastError());
         return;
      }

      // 投递一次接收,由于接收都需要使用这个函数来投递一个接收的准备

      if ((PerIoData = (LPPER_IO_OPERATION_DATA) GlobalAlloc(GPTR,          sizeof(PER_IO_OPERATION_DATA))) == NULL)
      {
         printf("GlobalAlloc() failed with error %d\n", GetLastError());
         return;
      }

      ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));
      PerIoData->BytesSEND = 0;
      PerIoData->BytesRECV = 0;
      PerIoData->DataBuf.len = DATA_BUFSIZE;
      PerIoData->DataBuf.buf = PerIoData->Buffer;

      Flags = 0;
      if (WSARecv(Accept, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags,
         &(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
      {
         if (WSAGetLastError() != ERROR_IO_PENDING)
         {
            printf("WSARecv() failed with error %d\n", WSAGetLastError());
            return;
         }
      }
   }
}
//工作线程
DWORD WINAPI ServerWorkerThread(LPVOID CompletionPortID)
{
   HANDLE CompletionPort = (HANDLE) CompletionPortID;
   DWORD BytesTransferred;
   LPOVERLAPPED Overlapped;
   LPPER_HANDLE_DATA PerHandleData;
   LPPER_IO_OPERATION_DATA PerIoData;
   DWORD SendBytes, RecvBytes;
   DWORD Flags;
  
   while(TRUE)
   {
      //完成端口有消息来了
      if (GetQueuedCompletionStatus(CompletionPort, &BytesTransferred,
         (LPDWORD)&PerHandleData, (LPOVERLAPPED *) &PerIoData, INFINITE) == 0)
      {
         printf("GetQueuedCompletionStatus failed with error %d\n", GetLastError());
         return 0;
      }

      //是不是有人退出了

      if (BytesTransferred == 0)
      {
         printf("Closing socket %d\n", PerHandleData->Socket);

         if (closesocket(PerHandleData->Socket) == SOCKET_ERROR)
         {
            printf("closesocket() failed with error %d\n", WSAGetLastError());
            return 0;
         }

         GlobalFree(PerHandleData);
         GlobalFree(PerIoData);
         continue;
      }

      //

      if (PerIoData->BytesRECV == 0)
      {
         PerIoData->BytesRECV = BytesTransferred;
         PerIoData->BytesSEND = 0;
      }
      else
      {
         PerIoData->BytesSEND += BytesTransferred;
      }

      if (PerIoData->BytesRECV > PerIoData->BytesSEND)
      {

         // Post another WSASend() request.
         // Since WSASend() is not gauranteed to send all of the bytes requested,
         // continue posting WSASend() calls until all received bytes are sent.

         ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));

         PerIoData->DataBuf.buf = PerIoData->Buffer + PerIoData->BytesSEND;
         PerIoData->DataBuf.len = PerIoData->BytesRECV - PerIoData->BytesSEND;

         if (WSASend(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &SendBytes, 0,
            &(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
         {
            if (WSAGetLastError() != ERROR_IO_PENDING)
            {
               printf("WSASend() failed with error %d\n", WSAGetLastError());
               return 0;
            }
         }
      }
      else
      {
         PerIoData->BytesRECV = 0;

         // Now that there are no more bytes to send post another WSARecv() request.

         Flags = 0;
         ZeroMemory(&(PerIoData->Overlapped), sizeof(OVERLAPPED));

         PerIoData->DataBuf.len = DATA_BUFSIZE;
         PerIoData->DataBuf.buf = PerIoData->Buffer;

         if (WSARecv(PerHandleData->Socket, &(PerIoData->DataBuf), 1, &RecvBytes, &Flags,
            &(PerIoData->Overlapped), NULL) == SOCKET_ERROR)
         {
            if (WSAGetLastError() != ERROR_IO_PENDING)
            {
               printf("WSARecv() failed with error %d\n", WSAGetLastError());
               return 0;
            }
         }
      }
   }
}

发表在 article | 标签为 | C++ socket 编程已关闭评论

大b和小b的换算关系

在计算机网络、IDC机房中,其宽带速率的单位用bps(或b/s)表示;换算关系为:1Byte=8bit






1B=8b





---------- 1B/s=8b/s(或1Bps=8bps)






1KB=1024B



---------- 1KB/s=1024B/s




1MB=1024KB ---------- 1MB/s=1024KB/s




在实际上网应用中,下载软件时常常看到诸如下载速度显示为128KB(KB/s),103KB/s等等宽带速率大小字样,因为ISP提供的线路带宽使用的 单位是比特,而一般下载软件显示的是字节(1字节=8比特),所以要通过换算,才能得实际值。然而我们可以按照换算公式换算一下:
128KB/s=128×8(Kb/s)=1024Kb/s=1Mb/s即:128KB/s=1Mb/s






理论上:2M(即2Mb/s)宽带理论速率是:256KB/s(即2048Kb/s),实际速率大约为80--200kB/s;(其原因是受用户计算机性 能、网络设备质量、资源使用情况、网络高峰期、网站服务能力、线路衰耗,信号衰减等多因素的影响而造成的)。4M(即4Mb/s)的宽带理论速率 是:512KB/s,实际速率大约为200---440kB/s

上行速率是指用户电脑向网络发送信息时的数据传输速率,下行速率是指网络向用户电脑发送信息时的传输速率。比如用 FTP上传文件到网上去,影响上传速度的就是“上行速率”;而从网上下载文件,影响下载速度的就是“下行速率”。当然,在实际上传下载过程中,线路、设备 (含计算机及其他设备)等的质量也会对速度造成或多或少的影响。宽带网速计算方法.

基础知识:
在计算机科学中,bit是表示信息的最小单位,叫做二进制位;一般用0和1表示。Byte叫做字节,由8个位(8bit)组成一个字节(1Byte),用 于表示计算机中的一个字符。bit与Byte之间可以进行换算,其换算关系为:1Byte=8bit(或简写为:1B=8b);在实际应用中一般用简称, 即1bit简写为1b(注意是小写英文字母b),1Byte简写为1B(注意是大写英文字母B)。
在计算机网络或者是网络运营商中,一般,宽带速率的单位用bps(或b/s)表示;bps表示比特每秒即表示每秒钟传输多少位信息,是bit per second的缩写。在实际所说的1M带宽的意思是1Mbps(是兆比特每秒Mbps不是兆字节每秒MBps)。
建议用户记住以下换算公式:
1B=8b 1B/s=8b/s(或1Bps=8bps)
1KB=1024B 1KB/s=1024B/s
1MB=1024KB 1MB/s=1024KB/s

规范提示:实际书写规范中B应表示Byte(字节),b应表示bit(比特),但在平时的实际书写中有的把bit和Byte都混写为b ,如把Mb/s和MB/s都混写为Mb/s,导致人们在实际计算中因单位的混淆而出错。切记注意!!!

实例:在我们实际上网应用中,下载软件时常常看到诸如下载速度显示为128KBps(KB/s),103KB/s等等宽带速率大小字样,因为ISP提供的 线路带宽使用的单位是比特,而一般下载软件显示的是字节(1字节=8比特),所以要通过换算,才能得实际值。然而我们可以按照换算公式换算一下:
128KB/s=128×8(Kb/s)=1024Kb/s=1Mb/s即128KB/s=1Mb/s。

案例1: 某用户反映,为什么我的网速和我办的带宽不一样? 我办的是4M 的宽带,可为什么我测试却只有2百多K的网速啊? 是不是电信骗了我?没有给我开4M哟 ?
案例分析:尊敬的用户,这只是误会。这可能有几个你不理解的原因:第一,实际网速单位是Mb/s,不是MB/s,而你所说的2百多K,其实际是指2百多 KB/s(即2百多千字节每秒)不是2百多Kb/s(即2百多千比特每秒),通常情况下都是说简称如250KB/s或250Kb/s说成250K。第二, 宽带4Mb/s=512KB/s并且这只是技术上的最大理论值,而不是所达到的实际值,一般正常情况下技术上的最大理论值为4Mb/s的宽带实际值可以达 200KB/s至440KB/s。因为宽带速率要受到很多因素(比如用户计算机性能、资源使用情况、网络高峰期、网站服务能力、信号衰耗、线路衰耗、距离 远近等)的影响,所以导至实际值与技术上的最大理论值有偏差。第三,网络运营商提供的宽带速率单位中,"bps"是指"bit per second"。而实际速度所指的bps是指"Byte per second"。所以要经过换算,而1Byte=8bit,在计算网速的上行速度或下行速度,都必须将数值除以8即把bit转化为Byte。例如:下行速 度(即下载速度)为1Mb/s,其换算成等价值就是128KBps ;换算方法:1Mbps=1024/8(KBps)=128KBps即128KByte/s 。

案例2: 某用户反映, 我办的是4M 的宽带, 为什么我的网速比通常情况下都慢哟,而且还经常掉线?是不是电信骗了我?没有给我开4M哟 ?
案例分析:尊敬的用户,这只是误会。导致网速慢和经常掉线,通常情况下有几种可能的原因:第一、计算机感染病毒较严重;第二:计算机软硬件配置及性能;第 三、上网终端质量、网线质量、线路传输负载;第四、线路接触是否良好、电源电压是否稳定等问题;第五、外界信号干扰、信号衰减、线路衰耗及线路距离长短; 第六、私自或不规范组网;第七,网卡质量不好或没有插好;第八、安装了多种杀毒软件及防火墙或同时运行过多的程序;第九、通信协议设置和防火墙的配置等等 原因;对于本案例中,该用户的情况经查明,该用户网速慢和掉线的原因是:第一、该用户的电脑感染了多种病毒,导致内存被占用,CPU使用率较高,经常达 100%;影响了电脑性能,导致网速慢;第二、该用户办理的是ADSL拨号上网,因不规范的私自组网,导致线路传输负载加重,影响线路传输流量,造成网速 慢并且经常掉线。第三、网线RJ45与HUB的接头接触不良好和电源电压不稳

发表在 article | 大b和小b的换算关系已关闭评论

Nginx实践1 利用proxy_store实现高效的静态文件分布缓存服务器

Nginx作为一个后起之秀,他的迷人之处已经让很多人都投入了他的怀抱。配置简单,实现原理简单。做一个负载平衡的再好不过了。

其原理:

简单介绍一下他的安装及配置过程

官方网站
http://wiki.codemongers.com/Main

一、依赖的程序

1. gzip module requires zlib library
2. rewrite module requires pcre library
3. ssl support requires openssl library

二、安装
./configure
make
make install

默认安装的路径是/usr/local/nginx

更多的安装配置
./configure --prefix=/usr/local/nginx
--with-openssl=/usr/include (启用ssl)
--with-pcre=/usr/include/pcre/ (启用正规表达式)
--with-http_stub_status_module (安装可以查看nginx状态的程序)
--with-http_memcached_module (启用memcache缓存)
--with-http_rewrite_module (启用支持url重写)

三、启动及重启
启动:nginx
重启:kill -HUP `cat /usr/local/nginx/logs/nginx.pid`
测试配置文件:nginx -t

简单吧,安装,启动都比较方便。

四、配置文件
http://wiki.codemongers.com/NginxFullExample

#运行用户

user  nobody nobody;

#启动进程

worker_processes  5;

#全局错误日志及PID文件


error_log  logs/error.log notice;

pid        logs/nginx.pid;

#工作模式及连接数上限

events {

  #工作模式有:select(标准模式),poll(标准模式),kqueue(高效模式,适用FreeBSD 4.1+, OpenBSD 2.9+, NetBSD 2.0 and MacOS X),

  #epoll(高效模式,本例用的。适用Linux 2.6+,SuSE 8.2,),/dev/poll(高效模式,适用Solaris 7 11/99+, HP/UX 11.22+ (eventport), IRIX 6.5.15+ 和 Tru64 UNIX 5.1A+)

  use epoll;

  worker_connections      1024;

}

#设定http服务器,利用它的反向代理功能提供负载均衡支持

http {

  #设定mime类型

  include      conf/mime.types;

  default_type  application/octet-stream;

  #设定日志格式

  log_format main        '$remote_addr - $remote_user [$time_local] '

                         '"$request" $status $bytes_sent '

                         '"$http_referer" "$http_user_agent" '

                         '"$gzip_ratio"';
  log_format download    '$remote_addr - $remote_user [$time_local] '

                         '"$request" $status $bytes_sent '

                         '"$http_referer" "$http_user_agent" '

                         '"$http_range" "$sent_http_content_range"';

  #设定请求缓冲

  client_header_buffer_size    10k;

  large_client_header_buffers  4 4k;

  

  #开启gzip模块,要求安装gzip 在运行./config时要指定

  gzip on;

  gzip_min_length  1100;

  gzip_buffers    4 8k;

  gzip_types      text/plain;

  output_buffers  1 32k;

  postpone_output  1460;

  

  #设定访问日志

  access_log  logs/access.log  main;

  client_header_timeout  3m;

  client_body_timeout    3m;

  send_timeout          3m;

  sendfile                on;

  tcp_nopush              on;

  tcp_nodelay            on;

  keepalive_timeout  65;

  

  #设定负载均衡的服务器列表

  upstream backserver {

  #weigth参数表示权值,权值越高被分配到的几率越大

  #本例是指在同一台服务器,多台服务器改变ip即可

  server 127.0.0.1:8081 weight=5;

  server 127.0.0.1:8082;

  server 127.0.0.1:8083;

  }
  #设定虚拟主机,默认为监听80端口,改成其他端口会出现问题

  server {

    listen         80;

    server_name    test.com
 www.test.com
;

    charset utf8;

    #设定本虚拟主机的访问日志

    access_log  logs/test.com.log  main;

    #如果访问 /images/*, /js/*, /css/* 资源,则直接取本地文件,不用转发。但如果文件较多效果不是太好。

    location ~ ^/(images|js|css)/  {

        root    /usr/local/testweb;

        expires 30m;

    }

    

    #对 "/" 启用负载均衡

    location / {

       proxy_pass      http://backserver
;

       proxy_redirect          off;

       proxy_set_header        Host $host;

       proxy_set_header        X-Real-IP $remote_addr;

       proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;

       client_max_body_size    10m;

       client_body_buffer_size 128k;

       proxy_connect_timeout  90;

       proxy_send_timeout      90;

       proxy_read_timeout      90;

       proxy_buffer_size      4k;

       proxy_buffers          4 32k;

       proxy_busy_buffers_size 64k;

       proxy_temp_file_write_size 64k;

    }

    #设定查看Nginx状态的地址,在运行./config 要指定,默认是不安装的。

    location /NginxStatus {

       stub_status            on;

       access_log              on;

       auth_basic              "NginxStatus";

       #是否要通过用户名和密码访问,测试时可以不加上。conf/htpasswd 文件的内容用 apache
 提供的 htpasswd 工具来产生即可       

       #auth_basic_user_file  conf/htpasswd;

    }

}

有详细的说明
-----------------------------------------------------------------------------------

 

 

曾经写过是否要放弃使用varnish/squid, 经过几天的实验,终于找到一种比较理想的解决方案:

直接使用proxy模块的proxy_store来实现分布mirror.

首先说说我的需求:

1. 我需要将一些静态文件从应用服务器剥离, 负载到其他的节点.
2. 这些文件主要是静态Html和图片,包括缩略图. 这些文件一旦创建,更新的频率很少.
3. 在某些时候需要手动立即从各个分布节点删除或更新某些文件
4. 尽可能减少应用服务器的请求, 进而减少内网的流量

之前,我分别使用了squid和varnish.
最初用的squid,还凑合.不过,squid在高负载下会出现停滞甚至crash或者是空白页.
于是换成varnish.
varnish也是老毛病,偶尔也会crash.

二者的共同点,就是当cache快满的时候,效率会急剧下降, 同时,对主服务器的请求甚至都
阻塞了整个内网.

要解决这个情况,varnish需要手动重启, squid则需要清除整个缓存目录.

对于varnish, 由于是纯内存的加速,因此,无法将cache设置太大,否则用上swap, 基本上是几倍的速度下降,
而且很容易就段违例了. 于是,当bots访问网站的时段, 就是噩梦产生的时候, 由于爬虫遍历太多的文件,
造成缓存很快溢出,于是频繁的invalid,此时,内网的带宽占用能达到100m以上….

可能有人说,为什么不用NFS. NFS的问题主要是锁的问题. 很容易造成死锁, 只有硬件重启才能解决.

为了脱离这个噩梦,我决定试验nginx的proxy_store. 如果使用Lighty,倒是非常简单,因为有mod_cache,配合lua,
会很灵活. 不过nginx的proxy_store并非是一个cache,因为它不具备expires, 新的cache模块仍在开发中.
不过经过仔细考量, 我惊喜的发现,其实这正是我想要的, 因为在我的需求中,绝大多数的文件都是不过期的,因而也无必要
去和后端服务器验证是否过期.

配置其实并不太复杂,但是过程有些曲折, 基本的思路是:
nginx首先检查本地是否有请求的文件,如果有直接送出,没有则从后端请求,并将结果存储在本地.

第一个方案,是基于error_page来实现的:

upstream backend{
server 192.168.8.10:80;
}
server {
listen 80;
access_log /logs/cache.log main;
server_name blog.night9.cn www.night9.cn night9.cn;
proxy_temp_path /cache/temp;
root /cache/$host;
location / {
index index.shtml;
error_page 404 = /fetch$uri;
}
ssi on;
location /fetch {
internal;
proxy_pass http://backend;
proxy_store on;
proxy_store_access user:rw group:rw all:rw;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Via "s9/nginx";
alias /cache/$host;
}
#对于请求目录的情况下要特殊对待
location ~ /$ {
index index.shtml;
error_page 403 404 = @fetch;
}
location @fetch {
internal;
proxy_pass http://backend;
proxy_store /cache/$host${uri}index.shtml;
proxy_store_access user:rw group:rw all:rw;
proxy_set_header Host $host;
proxy_set_header Via "s9/nginx";
proxy_set_header X-Real-IP $remote_addr;
}
}
 

这个方案对于普通的情况下,基本满足.

缓存是做到了,但是如何实现更新呢?
其实很简单,只要将指定url的从本地cache目录删除即可.
因为proxy_store会按照实际请求的url地址建立相应的目录结构.

于是,我写了一个fastcgi, 只要将需要清楚的url传递给它,从cache目录中删除.
其实可以用perl_module实现,但是考虑到独立fastcgi服务更为稳定,还是和以前的统计一样,
用perl的CGI::Fast模块实现, 替换了10几行代码就搞定了.

事情本来就该告一段,不过,由于主服务器上使用了SSI, 新的问题就来了:
我们希望SSI的解析是在子节点上进行,而不是在主服务器上进行, 这样我们可以独立更新相应
区块的文件即可, 否则就需要清除所有的shtml文件,这是比较可怕的.

但是,Nginx对于SSI的subrequest无法使用error_page来重定向.(不确定是否是bug,不过如果允许
的确容易造成死循环).

于是,一个更为简单的方案就诞生了:

set $index 'index.shtml';
set $store_file $request_filename;
if ($uri ~ /$ ){
set $store_file $request_filename$index;
rewrite (.*) $1index.shtml last;
}
location / {
index index.shtml;
proxy_store on;
proxy_temp_path /cache/temp;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Via "s9/nginx";
proxy_store_access user:rw group:rw all:rw;
if ( !-e $store_file ) {
proxy_pass http://backend;
}
}
 

Wow! 更为简单.
应该感谢Nginx的Rewrite模块, 这点也是我用Nginx替换Lighttpd的一个主要原因.

好了,我可以忘掉varnish,squid了.

如果有兴趣的人想使用, 请一定注意:
这个方案对静态文件更为有效,如果要加速动态请求,还是要用varnish

说道加速, 利用Memcached和nginx配合可以迅速提升访问动态页面的速度,
有时间再说.

发表在 web server | 标签为 | Nginx实践1 利用proxy_store实现高效的静态文件分布缓存服务器已关闭评论

打建性能比squid高很多的varnish服务器

https://www.varnish-cache.org/

最新安装:https://www.varnish-cache.org/docs/3.0/installation/install.html#source-or-packages

varnish是一款高性能的开源HTTP加速器,挪威最大的在线报纸 Verdens Gang (http://www.vg.no) 使用3台Varnish代替了原来的12台squid,

性能比以前更好。
varnish的作者Poul-Henning Kamp是FreeBSD的内核开发者之一,他认为现在的计算机比起1975年已经复杂许多。在1975年时,储存媒介只有两

种:内存与硬盘。但现在计算机系统的内存除了主存外,还包括了cpu内的L1、L2,甚至有L3快取。硬盘上也有自己的快取装置,因此squid

cache自行处理物件替换的架构不可能得知这些情况而做到最佳化,但操作系统可以得知这些情况,所以这部份的工作应该交给操作系统处理,

这就是 Varnish cache设计架构。

1.下载源码包编译安装:

cd /usr/local/src && wget http://nchc.dl.sourceforge.net/sourceforge/varnish/varnish-1.1.1.tar.gz
tar zxvf /usr/local/src/varnish-1.1.1.tar.gz
cd /usr/local/src/varnish-1.1.1
./autogen.sh
./configure –enable-debugging-symbols –enable-developer-warnings –enable-dependency-tracking
注:如果你的gcc版本是4.2.0或更高的版本,可以加上–enable-extra-warnings编译参数,在出错时,得到附加的警告信息。
我这里是用源码包安装的,如果你是redhat或centos可以用rpm包来安装(rpm下载位置:http: //sourceforge.net/project/showfiles.php?

group_id=155816&package_id=173643&release_id=533569).

2. 建立cache目录:
mkdir -p /cache/varnish/V && chown -R nobody:nobody /cache

3.编写启动文件:

cd /usr/local/varnish/sbin
vi start.sh
内容如下:
#!/bin/sh
# file: go.sh
date -u
/usr/local/varnish/sbin/varnishd \
-a 10.0.0.129:80 \
-s file,/cache/varnish/V,1024m \
-f /usr/local/varnish/sbin/vg.vcl.default \
-p thread_pool_max=1500 \
-p thread_pools=5 \
-p listen_depth=512 \
-p client_http11=on \

-T 0.0.0.0:8082
注:-a 是指定后端服务器的ip或hostname,就象squid做revese proxy时的originserver.
不过这个也可以在vcl里面写。
-f 是指定所用的vcl的文件。
-s 指定cache目录的存储类型,文件位置和大小。
-p 是指定varnish的启动的一些启动参数,可以根据自己的机器配置来优化varnish的性能。

-T address:port # telnet管理地址及其端口
其他参数已经参数的具体含义可以用varnishd –help 来查看。

4.编写vcl:
我的vcl如下:

backend default {
set backend.host = “127.0.0.1″;
set backend.port = “http”;
}

#我用的是一台机器做测试,使用的backend用的是127.0.0.1:80.如果varnish机器和后台的机器分开的。
写上对应的机器的ip或hostname就可以了。

sub vcl_recv {

if (req.request != “GET” && req.request != “HEAD”) {
pipe;
}

if (req.http.Expect) {
pipe;
}

if (req.http.Authenticate || req.http.Cookie) {
pass;
}

if (req.request == “GET” && req.url ~ “\.(gif|jpg|swf|css|js)$”) {
lookup;
}
lookup;
}

sub vcl_pipe {
pipe;
}

sub vcl_pass {
pass;
}

sub vcl_hash {
hash;
}

sub vcl_hit {
if (!obj.cacheable) {
pass;
}
deliver;
}

sub vcl_timeout {
discard;
}

sub vcl_discard {
discard;
}

如果是多个站点在不同的originserver时,可以使用下面配置:

backend www {
set backend.host = “www.jackbillow.com”;
set backend.port = “80″;
}

backend images {
set backend.host = “images.jackbillow.com”;
set backend.port = “80″;
}

sub vcl_recv {
if (req.http.host ~ “^(www.)?jackbillow.com$”) {
set req.http.host = “www.jackbillow.com”;
set req.backend = www;
} elsif (req.http.host ~ “^images.jackbillow.com$”) {
set req.backend = images;
} else {
error 404 “Unknown virtual host”;
}

5.启动varnish:

/usr/local/varnish/sbin/start.sh

Mon Sep 3 03:13:19 UTC 2007
file /cache/varnish/V/varnish.tEKXXx (unlinked) size 1073741824 bytes (262144 fs-blocks, 262144 pages)
Using old SHMFILE

ps waux | grep varnish
root 16254 0.0 0.0 11200 708 ? Ss 10:43 0:00 /usr/local/varnish/sbin/varnishd -a 10.0.0.129:80 -s /varnish/V,1024m

-f /usr/local/varnish/sbin/vg.vcl.default -p thread_pool_max 1500 -p thread_pools 5 -p listen_depth 512 -p client_http11 on
nobody 16255 0.0 0.1 1152552 1808 ? Sl 10:43 0:00 /usr/local/varnish/sbin/varnishd -a 10.0.0.129:80 -s

file,/cache/varnish/V,1024m -f /usr/local/varnish/sbin/vg.vcl.default -p thread_pool_max 1500 -p thread_pools 5 -p

listen_depth 512 -p client_http11 on

看到上面信息说明varnish正确启动,恭喜你,你已经配置成功了。:)

 

-----------------------------------------------------------------------------------------

varnish cache 配置过程

和Squid相比Varnish更适合在大内存的server上使用。

软件:varnish-1.1.2.tar.gz

安装过程
#/usr/sbin/groupadd www -g 48
#/usr/sbin/useradd -u 48 -g www www
#mkdir -p /var/vcache
#chmod +w /var/vcache
#chown -R www:www /var/vcache
#mkdir -p /var/log/varnish
#chmod +w /var/log/varnish
#chown -R www:www /var/log/varnish
#cd /data/software
#tar zxvf varnish-1.1.2.tar.gz
#cd varnish-1.1.2
#./configure --prefix=/usr/local/varnish
#make && make install

编辑Varnish配置文件
#vi /usr/local/varnish/vcl.conf

backend webserver {
       set backend.host = "10.10.10.8";
       set backend.port = "80";
}

acl purge {
       "localhost";
       "127.0.0.1";
       "10.10.10.0"/24;
}

sub vcl_recv {
        remove req.http.X-Forwarded-For;
        set    req.http.X-Forwarded-For = client.ip;
        if (req.request == "PURGE") {
               if (!client.ip ~ purge) {
                       error 405 "Not allowed.";
               }
               lookup;
       }

       if (req.http.host ~ "(a|b|c).test.com") {
               set req.backend = webserver;
              if (req.url ~ "\.(png|gif|jpg|swf|css|js)$") {
                       lookup;
        }
               else {
                       pass;
               }
       }

       else {
               error 404 "Test Cache Server";
               pipe;
       }
}

sub vcl_hash {
    set req.hash += req.url;
    if (req.http.host) {
        set req.hash += req.http.host;
    } else {
        set req.hash += server.ip;
    }
    hash;
}

sub vcl_pipe {
        set req.http.connection = "close";
        #pipe;
}

sub vcl_hit {
        if (!obj.cacheable) {
                pass;
        }
       if (req.request == "PURGE") {
               set obj.ttl = 0s;
               error 200 "Purged.";
       }
        deliver;
}

sub vcl_miss {
       if (req.request == "PURGE") {
               error 404 "Not in cache.";
       }
}

sub vcl_fetch {
               set obj.ttl = 180s;
               #set    obj.http.X-Varnish-IP = server.ip;
               set    obj.http.Varnish = "Tested by Kevin";
}

启动Varnish
#/usr/local/varnish/sbin/varnishd -n /var/vcache -f /usr/local/varnish/vcl.conf -a 0.0.0.0:80 -s file,/var/vcache/varnish_cache.data,4G -u apache -w 30000,51200,10 -T 127.0.0.1:3500 -p client_http11=on -p thread_pools=4

启动日志记录
#/usr/local/varnish/bin/varnishncsa -n /var/vcache -w /var/log/varnish/varnish.log &

补充几条相关命令
查看Varnish状态
/usr/local/varnish/bin/varnishstat -n /var/vcache/

查看访问最多的Referer
/usr/local/varnish/bin/varnishtop -n /var/vcache/ -i rxheader -I Referer

查看访问最多的URL
/usr/local/varnish/bin/varnishtop -n /var/vcache/ -i rxurl

等了N久还不见新的版本出来,于是忍不住先学习一下,主要是看man page。

基本明白,但英语还是太差,理解能力也有限,有些细微之处不很明白,比如pass和pipe的区别等等。

安装过程就不说了,无非就是configure/make/make install,配置样例也都有

在昨天配置varnish的时候发现,man里提供的配置样例中有一段是这样的

if (req.http.Authenticate || req.http.Cookie) {
pass;
}

但是实际上这段配置在测试过程中造成了一些麻烦,情况很奇怪,怀疑是varnish的bug。网站图片显示不正常,文字貌似没问题,抓包看,竟然发现在客户端请求图片的时候,varnish把上一次回送的HTML文本内容又送了一遍。

由于不太清楚pass和pipe的区别,出于尝试目的于是我把配置改为:

if (req.http.Authenticate ){
pass;
}
if(req.http.Cookie) {
pipe;
}

也就正常了。

于是再次尝试一下,暂时把自己BLOG的域名指到一台跑varnish的烂PC上,测试一下看看,获取些实际运行经验。打算跑个几天再改回来。

昨天下班后修改DSN,本地大约过了5个小时,生效,访问www.2tutu.com 通过varnish缓存。

早上来看了下,varnish总共处理1395个请求,缓存命中是1132,看样子对于ZBLOG这样静态内容为主的站点,缓存命中还是比较高的。

自己的网站访问量并不大,其实最好能找个访问量比较大的站点进行一下实际测试,呵呵。

man page意译如下:

VCL语法比较简单,和C类似,if(){}的形式,=和==的区别,!、&&和||等等。但\符号没有特别的意思。
VCL里除了用==、!、&&、||做逻辑判断意外,还可以用~来表示与正则表达式或ACL的匹配。
VCL其实只是配置,并不是真正的编程语言,没有循环,没有自定义变量。

声明Backend
backend 名称 {
set backend.host = "域名";
set backend.port = "端口";
}
比如
backend www {
set backend.host = "www.example.com";
set backend.port = "http";
}
声明的Backend可以用在判断请求针对哪个后端服务器
if (req.http.host ~ "^(www.)?example.com$") {
{
set req.backend = www;
}

声明ACL
acl 名称 {
"IP";
"IP子网"/反掩码位数;
! "IP或IP子网"/反掩码位数;
}
比如
acl local {
"locahost"; /* myself */
"10.0.0.1"/8; /* and everyone on the local network */
! "10.0.0.23"; /* except for the dialin router */
}
判断ACL也很简单
if (client.ip ~ local) {
pipe;
}

还可以定义子程序
sub pipe_if_local {
if (client.ip ~ local) {
pipe;
}
}
用call来调用
call pipe_if_local;

内置的例程
vcl_recv
有请求到达后成功接收并分析时被调用,一般以以下几个关键字结束。
error code [reason] 返回code给客户端,并放弃处理该请求
pass 进入pass模式,把控制权交给vcl_pass
pipe 进入pipe模式,把控制权交给vcl_pipe
lookup 在缓存里查找被请求的对象,根据查找结果把控制权交给vcl_hit或vcl_miss

vcl_pipe
进入pipe模式时被调用。请求被直接发送到backend,后端和客户端之间的后继数据不进行处理,只是简单传递,直到一方关闭连接。一般以以下几个关键字结束。
error code [reason]
pipe

vcl_pass
进入pass模式时被调用。请求被送到后端,后端应答数据送给客户端,但不进入缓存。同一连接的后继请求正常处理。一般以以下几个关键字结束。
error code [reason]
pass

vcl_hash
目前不使用

vcl_hit
在lookup以后如果在cache中找到请求的内容事调用。一般以以下几个关键字结束。
error code [reason]
pass
deliver 将找到的内容发送给客户端,把控制权交给vcl_deliver.

vcl_miss
lookup后但没有找到缓存内容时调用,可以用于判断是否需要从后端服务器取内容。一般以以下几个关键字结束。
error code [reason]
pass
fetch 从后端取得请求的内容,把控制权交给vcl_fetch.

vcl_fetch
从后端取得内容后调用。一般以以下几个关键字结束。
error code [reason]
pass
insert 将取到的内容插入缓存,然后发送给客户端,把控制权交给vcl_deliver

vcl_deliver
缓存内容发动给客户端前调用。一般以以下几个关键字结束。
error code [reason]
deliver 内容发送给客户端

vcl_timeout
在缓存内容到期前调用。一般以以下几个关键字结束。
fetch 从后端取得该内容
discard 丢弃该内容

vcl_discard
由于到期或者空间不足而丢弃缓存内容时调用。一般以以下几个关键字结束。
discard 丢弃
keep 继续保留在缓存里

如果这些内置例程没有被定义,则执行缺省动作

一些内置的变量
now 当前时间,标准时间点(1970?)到现在的秒数

backend.host 后端的IP或主机名
backend.port 后端的服务名或端口

请求到达后有效的变量
client.ip 客户端IP
server.ip 服务端IP
req.request 请求类型,比如GET或者HEAD或者POST
req.url 请求的URL
req.proto 请求的HTTP版本号
req.backend 请求对应的后端
req.http.header 对应的HTTP头

往后段的请求时有效的变量
bereq.request 比如GET或HEAD
bereq.url URL
bereq.proto 协议版本
bereq.http.header HTTP头

从cache或后端取到内容后有效的变量
obj.proto HTTP协议版本
obj.status HTTP状态代码
obj.response HTTP状态信息
obj.valid 是否有效的HTTP应答
obj.cacheable 是否可以缓存的内容,也就是说如果HTTP返回是200、203、300、301、302、404、410并且有非0的生存期,则为可缓存
obj.ttl 生存期,秒
obj.lastuse 上一次请求到现在间隔秒数

对客户端应答时有效的变量
resp.proto response的HTTP版本
resp.status 回给客户端的HTTP状态代码
resp.response 回给客户端的HTTP状态信息
resp.http.header HTTP头

变量可以通过set来赋值或通过remove来删除(清空)
sub vcl_recv {
if (req.http.host ~ "^(www.)?example.com$") {
set req.http.host = "www.example.com";
}
}

sub vcl_fetch {
remove obj.http.Set-Cookie;
}

- -------------------------------------------------------------------------------------------------
 

我在设计系统架构时,进行了大胆的尝试,只用6台Web服务器(除开FLV视频存储服务器),达到了可承受4000万PV(页面访问量)的性能:

抛弃了 Apache,因为它能承受的并发连接相对较低;
抛弃了 Squid,因为它在内存利用、访问速度、并发连接、清除缓存等方面不如 Varnish;
抛弃了 PHP4,因为 PHP5 处理面向对象代码的速度要比 PHP4 快,另外,PHP4 已经不再继续开发;
抛弃了 F5 BIG-IP 负载均衡交换机,F5 虽然是个好东西,但由于价格不菲,多个部门多个产品都运行在其之上,流量大、负载高,从而导致性能大打折扣;

利用 Varnish cache 减少了90%的数据库查询,解决了MySQL数据库瓶颈;
利用 Varnish cache 的内存缓存命中加快了网页的访问速度;
利用 Nginx + PHP5(FastCGI) 的胜过Apache 10倍的高并发性能,以最少的服务器数量解决了PHP动态程序访问问题;
利用 Memcached 处理实时数据读写;
利用 HAProxy 做接口服务器健康检查;

经过压力测试,每台Web服务器能够处理3万并发连接数,承受4千万PV完全没问题。

保证4千万PV的并发连接数:(40000000PV / 86400秒 * 10个派生连接数 * 5秒内响应 * 5倍峰值) / 6台Web服务器 = 19290连接数

-------------------------------------------------------------------------------------------------------

创建Varnish配置文件:
vi /usr/local/varnish/vcl.conf

输入以下内容:
backend myblogserver {
set backend.host = "192.168.0.5";
set backend.port = "80";
}

acl purge {
"localhost";
"127.0.0.1";
"192.168.1.0"/24;
}

sub vcl_recv {
if (req.request == "PURGE") {
if (!client.ip ~ purge) {
error 405 "Not allowed.";
}
lookup;
}

if (req.http.host ~ "^blog.s135.com") {
set req.backend = myblogserver;
if (req.request != "GET" && req.request != "HEAD") {
pipe;
}
else {
lookup;
}
}
else {
error 404 "Zhang Yan Cache Server";
lookup;
}
}

sub vcl_hit {
if (req.request == "PURGE") {
set obj.ttl = 0s;
error 200 "Purged.";
}
}

sub vcl_miss {
if (req.request == "PURGE") {
error 404 "Not in cache.";
}
}

sub vcl_fetch {
if (req.request == "GET" && req.url ~ "\.(txt|js)$") {
set obj.ttl = 3600s;
}
else {
set obj.ttl = 30d;
}
}

这里,我对这段配置文件解释一下:
(1)、Varnish通过反向代理请求后端IP为192.168.0.5,端口为80的web服务器;
(2)、Varnish允许localhost、127.0.0.1、192.168.0.***三个来源IP通过PURGE方法清除缓存;
(3)、Varnish对域名为blog.s135.com的请求进行处理,非blog.s135.com域名的请求则返回“Zhang Yan Cache Server”;
(4)、Varnish对HTTP协议中的GET、HEAD请求进行缓存,对POST请求透过,让其直接访问后端Web服务器。之所以这样配置,是因为POST请求一般是发送数据给服务器的,需要服务器接收、处理,所以不缓存;
(5)、Varnish对以.txt和.js结尾的URL缓存时间设置1小时,对其他的URL缓存时间设置为30天。
5、启动Varnish

ulimit -SHn 51200
/usr/local/varnish/sbin/varnishd -n /var/vcache -f /usr/local/varnish/vcl.conf -a 0.0.0.0:80 -s file,/var/vcache/varnish_cache.data,1G -g www -u www -w 30000,51200,10 -T 127.0.0.1:3500 -p client_http11=on

6、启动varnishncsa用来将Varnish访问日志写入日志文件:

/usr/local/varnish/bin/varnishncsa -n /var/vcache -w /var/logs/varnish.log &

7、如果想配置成开机自动启动Varnish

vi /etc/rc.local

在末尾增加以下内容:

ulimit -SHn 51200
/usr/local/varnish/sbin/varnishd -n /var/vcache -f /usr/local/varnish/vcl.conf -a 0.0.0.0:80 -s file,/var/vcache/varnish_cache.data,1G -g www -u www -w 30000,51200,10 -T 127.0.0.1:3500 -p client_http11=on
/usr/local/varnish/bin/varnishncsa -n /var/vcache -w /var/logs/youvideo.log &

8、优化Linux内核参数

vi /etc/sysctl.conf

在末尾增加以下内容:

net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_syncookies = 1
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 5000    65000

再看看如何管理Varnish:
1、查看Varnish服务器连接数与命中率:

/usr/local/varnish/bin/varnishstat -n /var/vcache

输出的结果如下图显示: 

点击查看原图
2、通过Varnish管理端口进行管理:
用help看看可以使用哪些Varnish命令:

/usr/local/varnish/bin/varnishadm -T 127.0.0.1:3500 help

3、通过Varnish管理端口,使用正则表达式批量清除缓存:
(1)、例:清除类似http://blog.s135.com/a/zhangyan.html的URL地址):

/usr/local/varnish/bin/varnishadm -T 127.0.0.1:3500 url.purge /a/

(2)、例:清除类似http://blog.s135.com/tech的URL地址:

/usr/local/varnish/bin/varnishadm -T 127.0.0.1:3500 url.purge w*$

(3)、例:清除所有缓存:
/usr/local/varnish/bin/varnishadm -T 127.0.0.1:3500 url.purge *$

附1:2007年12月10日,我写了一个每天0点运行,按天切割Varnish日志,生成一个压缩文件,同时删除上个月旧日志的脚本(/var/logs/cutlog.sh):
/var/logs/cutlog.sh文件内容如下:

#!/bin/sh
# This file run at 00:00
date=$(date -d "yesterday" +"%Y-%m-%d")
pkill -9 varnishncsa
mv /var/logs/youvideo.log /var/logs/${date}.log
/usr/local/varnish/bin/varnishncsa -n /var/vcache -w /var/logs/youvideo.log &
mkdir -p /var/logs/youvideo/
gzip -c /var/logs/${date}.log > /var/logs/youvideo/${date}.log.gz
rm -f /var/logs/${date}.log
rm -f /var/logs/youvideo/$(date -d "-1 month" +"%Y-%m*").log.gz

设置在每天00:00定时执行:

/usr/bin/crontab -e
0 0 * * * /bin/sh /var/logs/cutlog.sh
 

发表在 web server | 标签为 | 68条评论

nginx+php+memcache+xcache+mysql安装与配置

nginx+php+memcache+xcache+mysql安装与配置

笔记:犹

链接:http://hi.baidu.com/avyou/blog/item/3ed08350f94516898c5430a9.html

安装系统的程序库-->安装数据库-->php需要的支持库-->安装php-->安装php扩展(memcache,xcache)-->安装nginx.

1.安装系统的程序库
yum -y install gcc gcc-c++ autoconf libjpeg libjpeg-devel libpng libpng-devel freetype freetype-devel libxml2 libxml2-devel zlib zlib-devel glibc glibc-devel glib2 glib2-devel bzip2 bzip2-devel ncurses ncurses-devel curl curl-devel

一般的,如果安装系统时选择了系统的开发库,只要再安装以下三个包就可以了,gd包也可以用rpm 安装,但gd-devel所依赖的其它包太多,所以后面将用源码包安装.

# rpm -ivh freetype-devel-2.2.1-19.el5.i386.rpm
# rpm -ivh libpng-devel-1.2.10-7.0.2.i386.rpm
# rpm -ivh libjpeg-devel-6b-37.i386.rpm
------------------------------------------------------------------------------
2.安装mysql数据库

为了方便,这里选择rpm包来安装.

# rpm -ivh perl-DBD-MySQL-3.0007-1.fc6.i386.rpm
# rpm -ivh mysql-server-5.0.22-2.1.0.1.i386.rpm
# rpm -ivh mysql-devel-5.0.22-2.1.0.1.i386.rpm //编译安装的php需要的mysql库

# /etc/rc.d/init.d/mysqld start
# mysqladmin -u root -p password yourpass
-------------------------------------------------------------------

3.编译安装PHP 5.2.6所需的支持库:

3.1. 安装libiconv

# tar zxvf libiconv-1.12.tar.gz
# cd libiconv-1.12/
# ./configure --prefix=/usr/local

# make && make install
-------------------------------------------------
3.2. 安装libmcrypt

# tar zxvf libmcrypt-2.5.8.tar.gz
# cd libmcrypt-2.5.8/
# ./configure
# make && make install
# ldconfig
# cd libltdl/
# ./configure --enable-ltdl-install
# make && make install
-------------------------------------------------
3.3.安装mhash

# tar zxvf mhash-0.9.9.tar.gz
# cd mhash-0.9.9/
# ./configure
# make && make install

# cp /usr/local/lib/libmcrypt.* /usr/lib
# ln -s /usr/local/lib/libmhash.so.2 /usr/lib/libmhash.so.2
# ldconfig
-----------------------------------------------------
3.4.安装mcrypt
# tar zxvf mcrypt-2.6.7.tar.gz
# cd mcrypt-2.6.7/
# ./configure
# make && make install
----------------------------------------------------
3.5.安装gd

# tar xvf gd-2.0.32.tar.tar
# cd gd2.0.32
# ./configure
# make && make install
--------------------------------------------------------------------
4.安装php(FastCGI模式)

说明:php-fpm-是 php-5.26的一个fpm管理补丁,在启用FastCGI模式时,可以平滑变更php.ini配置而无需重启php-cgi。没有php5.0 的php-fpm补丁包

# tar zxvf php-5.26.tar.gz
# gzip -cd php-5.2.6-fpm-0.5.8.diff.gz | patch -d php-5.2.6 -p1
# cd php-5.2.6/
# ./configure \
--prefix=/usr/local/php5 \ //php的安装路径
--with-mysql \ //与mysql库相关联
--with-iconv-dir=/usr/local \ //这里的路径要以前面libconv编译包一致
--with-freetype-dir \
--with-jpeg-dir \
--with-png-dir \
--with-zlib
--with-libxml-dir \
--with-gd \
--with-openssl \
--with-mcrypt \
--with-gd \
--enable-gd-native-ttf \
--enable-xml \
--enable-fastcgi \ //启用fastcgi模式
--enable-fpm \ //启用fpm管理
--enable-force-cgi-redirect \
--enable-mbstring \
--enable-inline-optimization \
--disable-debug

# make
# make install
# cp php.ini-dist /usr/local/php5/lib/php.ini

5.安装php5扩展模块

说明:
.Memcached是一个高性能的分布式的内存对象缓存系统。本文中的memcache.so是Memcached的客户端PHP扩展,与Xcache、eaccelerator、APC不是同一类东西,没有本质的联系。

.XCache 是一个开源的 opcode 缓存器/优化器, 这意味着他能够提高您服务器上的 PHP 性能. 他通过把编译 PHP 后的数据缓冲到共享内存从而避免重复的编译过程, 能够直接使用缓冲区已编译的代码从而提高速度. 通常能够提高您的页面生成速率 2 到5 倍, 降低服务器负载。eaccelerator、APC 也是 opcode 缓存器/优化器,跟xcache的功能类似,不能跟xcache一起使用。

.xcache还有数据缓存功能,功能跟Memcache类似,但效果不如Memcached。
--------------------------------------------------------------------------------------------
5.1 安装 memcache-2.23.tgz
# tar zxvf memcache-2.23.tgz
# /usr/local/php5/bin/phpize //生成Api版本号,Zend Module Api 号和Zend Extension Api号
#./configure --with-php-config=/usr/local/php5/bin/php-config
# make && make install //生成smemcache.so的路径:/usr/local/php5/lib/php/extensions/no-debug-non-zts-20060613/
--------------------------------------------------------------
5.2 安装xcache-1.2.2.tar.gz

# tar zxvf xcache-1.2.2.tar.gz
# cd xcache-1.2.2
# /usr/local/php5/bin/phpize
# ./configure --with-php-config=/usr/local/php5/bin/php-config --enable-xcache
# make && make install //生成xcache.so的路径:/usr/local/php5/lib/php/extensions/no-debug-non-zts-20060613/
--------------------------------------------------------------------------------------------
6.配置php5扩展模块

6.1 配置memcache

# vi /usr/local/php5/lib/php.ini

;/usr/local/webserver/php/etc/php.ini中的extension_dir = "./" //修改模块路径
/usr/local/webserver/php/etc/php.ini中的extension_dir = "/usr/local/php5/lib/php/extensions/no-debug-non-zts-20060613/"

extension = "memcache.so" //添加memcache.so模块

;display_errors = On
display_errors = Off //修改显示错误为off
---------------------------------------------------------
6.2 配置xcache

# vi xcache-1.2.2/xcache.ini

[xcache-common]
zend_extension = /usr/local/php5/lib/php/extensions/no-debug-non-zts-20060613/xcache.so

[xcache.admin]
xcache.admin.enable_auth = On //启用xcache管理认证
xcache.admin.user = "xcache" //验证名
; xcache.admin.pass = md5($your_password)
xcache.admin.pass = "e10adc3949ba59abbe56e057f20f883e" //md5 后的验证密码, 亦即 md5(您的密码), 留空则禁用管理页面.

[xcache]
xcache.shm_scheme = "mmap" // 选择低级别的共享存储器/分配算符安排执行
xcache.size = 32M //0 禁止, 非 0 则启用缓存器. 请注意您系统所允许的 mmap 最大值.
xcache.count = 1 //指定将 cache 切分成多少块. 参考 SplittedCache,可以用(cat /proc/cpuinfo |grep -c processor)命令查看
xcache.slots = 8K // 只是作为 hash 槽个数的参考值, 您可以放心地缓冲超过这个个数的项目
xcache.ttl = 0 //设置缓冲项目的 Ttl (Time To Live) 值, 0=永不过期
xcache.gc_interval = 0 //检查过期项目, 回收内存空间的间隔.

//同上, 不过用于数据缓冲而不是 opcode 缓冲.
xcache.var_size = 2M
xcache.var_count = 1
xcache.var_slots = 8K
xcache.var_ttl = 0
xcache.var_maxttl = 0
xcache.var_gc_interval = 300
xcache.test = Off
xcache.readonly_protection = Off
xcache.mmap_path = "/dev/zero" //对于 *nix, xcache.mmap_path 是 文件路径, 不是目录.
;xcache.cacher = On
;xcache.stat = On
;xcache.optimizer = On //启用优化器 (目前无效).

# cp xcache-1.2.2/xcache.ini /usr/local/php5/etc/xcache.ini
# cat /usr/local/php5/etc/xcache.ini >> /usr/local/php5/lib/php.ini
---------------------------------------------------------------------------------------------------------
6.3 安装xcache的web管理界面

说明:这一步留到安装完成nginx后来再来做,写在这里只为了顺着xcache的流程

# vi /var/data/www/md.php //获取md密码,在浏览器输入http://192.168.1.5/md.php,显示e10adc3949ba59abbe56e057f20f883e,得到后删除.

<?php
echo md5("password");
?>

--------------------------------

# rm -rf /var/data/www/md.php

# vi /usr/local/php5/lib/php.ini //修改php.ini文件
xcache.admin.user = "xcache"
xcache.admin.pass = "e10adc3949ba59abbe56e057f20f883e"

# cp -a xcache/admin /var/data/www/xcache
# chown -R www:www /var/data/www/xcache
# chmod -R +x /var/data/xcache

-------------------------------------------------------------------------
7.创建nginx的用户和组,并给虚拟主机目录分配权限

# groupadd www -g 101
# useradd -u 101 -g www www -s /bin/false
# mkdir -p /var/data/www/error
# chmod 755 /var/data/www
# chown -R www:www /var/data/www

---------------------------------------------------------------------

8.修改php-fpm配置文件,启动php-cgi进程

# vi /usr/local/php5/etc/php-fpm.conf //这里主要做几处修改即可,记得去掉里面的注释,否则启动出错!

--> <value name="pid_file">/usr/local/php5/logs/php-fpm.pid</value>
--> <value name="error_log">/usr/local/php5/logs/php-fpm.log</value>
--> <value name="user">www</value>
--> <value name="group">www</value>
--> <value name="max_children">25</value>
--> <value name="MaxSpareServers">35</value>
--> <value name="rlimit_files">10240</value>
--> <value name="max_requests">10240</value>

# ulimit -SHn 10240
# /usr/local/php5/sbin/php-fpm start //参数start|stop|quit|restart|reload|logrotate

-------------------------------------------------------------

9.安装与配置nginx

说明:
.gzip 模块需要 zlib 库
.rewrite 模块需要 pcre 库
.ssl 功能需要 openssl 库
----------------------------
9.1 安装pcre库

# tar zxvf pcre-7.7.tar.gz
# cd pcre-7.7/
# ./configure
# make && make install
-----------------------------------
9.2 安装nginx

# tar zxvf nginx-0.6.31.tar.gz
# cd nginx-0.6.31/
# ./configure --user=www --group=www --prefix=/usr/local/nginx --with-http_stub_status_module --with-http_ssl_module
# make && make install
-----------------------------------------
9.3 配置nginx

# mkdir /var/log/nginx
# chmod +w /var/log/nginx
# chown -R www:www /var/log/nginx
# cd /usr/local/nginx/conf
# cp nginx.conf nginx.conf.bak

# vi nginx.conf
-------------------------------------------------------------------------------------------------
user www www;
worker_processes 1;
error_log /var/log/nginx/error.log crit;
pid /var/log/nginx/nginx.pid;

events {
use epoll; //规定使用的I/O复用模式,Linux 2.6内核的epoll,FreeBSD用kqueue
worker_connections 2048;
}

http {
include mime.types;
default_type application/octet-stream;
keepalive_timeout 60;
sendfile on;
tcp_nopush on; //allows or forbids socket options TCP_NOPUSH on FreeBSD or TCP_CORK on Linux.
This option is only available when using sendfile.
tcp_nodelay on; //This directive allows or forbids the use of the socket option TCP_NODELAY. Only included in keep-alive connections.

fastcgi_connect_timeout 60;
fastcgi_send_timeout 180;
fastcgi_read_timeout 180;
fastcgi_buffer_size 128k;
fastcgi_buffers 4128k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;
fastcgi_temp_path /dev/shm;

gzip on;
gzip_min_length 1k;
gzip_buffers 48k;
gzip_http_version 1.1;
gzip_types text/plain application/x-javascript text/css text/html application/xml;

server {
listen 80;
server_name localhost;
index index.php index.html index.htm;
root /var/data/www;
charset utf8,gb2312;
log_format main '$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log /var/log/nginx/access.log main;

if (-d $request_filename){ //如果在浏览中输入"http://xxx/yy"会在目录yy后面加上"/"即"http://xxx/yy/"

rewrite ^/(.*)([^/])$ http://$host/$1$2/ permanent;
}

location ~ .*\.php?$ { //matches any request ending in .php?
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
error_page 404 http://192.168.1.5/error/404.html;
error_page 500 502 503 504 http://192.168.1.5/error/50x.html;

server {
listen 5200;
server_name localhost;
allow 192.168.1.101/32;
deny all;

location / {
root /var/www2/xcache;
index index.html index.htm;
}
location ~ .*\.php?$ {
root /var/www2/xcache;
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi.conf;
}
}

# server {
# listen 192.168.1.5;
# listen 192.168.1.5:80;
# server_name www.test3.com;
# location / {
# root /var/data/www3;
# index index.html index.htm;
# }
#
# }
}

---------------------------------------------------

# vi /usr/local/nginx/conf/fastcgi.conf //fastcgi的配置文件需要它,nginx才能支持php.也可以对fastcgi_params 进行简单修改

#fastcgi.conf
fastcgi_param GATEWAY_INTERFACE CGI/1.1;
fastcgi_param SERVER_SOFTWARE nginx;
fastcgi_param QUERY_STRING $query_string;
fastcgi_param REQUEST_METHOD $request_method;
fastcgi_param CONTENT_TYPE $content_type;
fastcgi_param CONTENT_LENGTH $content_length;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param SCRIPT_NAME $fastcgi_script_name;
fastcgi_param REQUEST_URI $request_uri;
fastcgi_param DOCUMENT_URI $document_uri;
fastcgi_param DOCUMENT_ROOT $document_root;
fastcgi_param SERVER_PROTOCOL $server_protocol;
fastcgi_param REMOTE_ADDR $remote_addr;
fastcgi_param REMOTE_PORT $remote_port;
fastcgi_param SERVER_ADDR $server_addr;
fastcgi_param SERVER_PORT $server_port;
fastcgi_param SERVER_NAME $server_name;
# PHP only, required if PHP was built with --enable-force-cgi-redirect
#fastcgi_param REDIRECT_STATUS 200;

--------------------------------------------------------------------------------------------------------------------------------
10.管理web服务

10.1管理命令

# /usr/local/php5/sbin/php-fmp restart
# /usr/local/nginx/sbin/nginx -t //测试配置文件,-c指定配置文件路径,-v显示 nginx 的版本,-V 显示 nginx 的版本,编译器版本和配置参数。
# /usr/local/nginx/sbin/nginx //启动nginx
# ps aux | grep '(PID|nginx)' //显示nginx的PID号2213
# kill -HUP 2213 //不用重启nginx,直接重新加载配置
# kill -HUP /var/log/nginx/nginx.pid //或者更新nginx.pid
------------------------------------------------------------------------
说明:

首先,使用新的可执行程序替换旧的,然后,发送USR2(kill –USR2 ROOT_PID)信号给主进程,主进程将重新命名它的.pid文件为nginx.pid..oldbin,然后执行新的可执行程序,依次启动新的主进程和工作进程。在这时,两个nginx实例会同时运行,一起处理输入的请求。需要逐步停止旧的实例,此时需要发送WINCH信号给就的主进程,然后它的工作进程开始关闭。一段时间后,旧的工作进程处理了所有已连接的请求后退出,就仅由新的工作进程来处理输入的请求。这时,因为旧的服务器还尚未关闭它监听的套接字,所以通过下面几步仍然可以恢复旧的服务器。

. 发送 HUP 信号给旧的主进程 - 它将在不重载配置文件的情况下启动它的工作进程
. 发送 QUIT 信号给新的主进程,要求其从容关闭其工作进程
. 发送 TERM 信号给新的主进程,迫使其退出
. 如果因为某些原因新的工作进程不能退出,向其发送 KILL 信号
------------------------------------------------------------------------
10.2管理日志

# vi /usr/local/nginx/sbin/nginxlog //日志截断脚本

#!/bin/sh
# This file run at 00:00
logdate=$(date -d "yesterday" +"%Y-%m-%d") //昨天的年月日
logdir=/var/log/nginx

gzip -c ${logdir}/access.log>${logdir}/${logdate}.log.gz

------------------------------------------------------

# echo ""> ${logdate}/access.log
# chmod +x /var/local/nginx/sbin/nginxlog
# crontab -e

0 0 * * * /usr/local/nginx/sbin/nginxlog>>/dev/null 2>&1

发表在 web server | 标签为 , , | nginx+php+memcache+xcache+mysql安装与配置已关闭评论

squid负载过高,必然DOWN机,垦请高手来分析

操作系统:solaris 10
服务器:SUN E2900   16G内存    4CPU   2个10000转SCSI硬盘
df -h

QUOTE:
/dev/dsk/c1t0d0s3       20G   4.4G    15G    23%    /var
swap                    27G     0K    27G     0%    /tmp
swap                    27G    16K    27G     1%    /var/run
/dev/dsk/c1t1d0s1       16G    11G   4.3G    73%    /proxy
/dev/dsk/c1t1d0s3       20G    14G   5.6G    72%    /cache1

squid版本是2.6,安装在/proxy下
squid.conf配置如下:

QUOTE:
http_port 10.1.1.1:8081
hierarchy_stoplist cgi-bin ?
hierarchy_stoplist -i ^https:\\ ?
acl QUERY urlpath_regex -i cgi-bin \? \.asp \.php \.jsp \.cgi
acl denyssl urlpath_regex -i ^https:\\
cache deny QUERY
cache deny denyssl
acl apache rep_header Server ^Apache
broken_vary_encoding allow apache

cache_mem 1024 MB
cache_swap_low 90
cache_swap_high 95
maximum_object_size 8192 KB
maximum_object_size_in_memory 32 KB

cache_dir ufs /proxy/var/cache 12000 48 256
cache_dir ufs /cache1 15000 48 256
access_log none
cache_log /cmproxy/var/logs/cache.log
cache_store_log none
mime_table /proxy/etc/mime.conf
pid_filename /proxy/var/logs/squid.pid
refresh_pattern ^ftp:           1440    20%     10080
refresh_pattern ^gopher:        1440    0%      1440
refresh_pattern .               0       20%     4320

acl all src 0.0.0.0/0.0.0.0
acl manager proto cache_object
acl localhost src 127.0.0.1/255.255.255.255
acl to_localhost dst 127.0.0.0/8
acl SSL_ports port 443 563
acl Safe_ports port 80                # http
acl Safe_ports port 21                # ftp
acl Safe_ports port 443 563           # https, snews
acl Safe_ports port 70                # gopher
acl Safe_ports port 210               # wais
acl Safe_ports port 1025-65535        # unregistered ports
acl Safe_ports port 280                # http-mgmt
acl Safe_ports port 488                # gss-http
acl Safe_ports port 591                # filemaker
acl Safe_ports port 777                # multiling http
acl CONNECT method CONNECT
acl SSL_gmcc_port port 81 443 563 7001 8080 8888 9087 9088 9315
acl our_networks src 10.0.0.0/8 192.168.0.0/16
http_access allow our_networks
http_access allow manager localhost
http_access deny manager
http_access allow SSL_gmcc_port
http_access deny !Safe_ports
http_access deny CONNECT !SSL_ports
http_access deny all
http_reply_access allow all

logfile_rotate 7
visible_hostname none
forwarded_for off
store_objects_per_bucket 50
icon_directory /proxy/share/icons
coredump_dir /cache1

 

同时在线连接数超过3K后,终端打开网页极慢,且squid进程僵死,无法通过squid -k shutdown停止,即使用squid -k kill 或kill -9 进程id也无效,只有重启机器

连接数

 

QUOTE:
netstat -an|grep 8081|grep EST|wc -l
3096

等待TIME_WAIT数

 

QUOTE:
netstat -an|grep TIME_WAIT|wc -l
5300

CPU占用率并不高

 

QUOTE:
#sar -u 3 5

SunOS 5.10 Generic_118833-02 sun4u    03/21/2007

08:16:10    %usr    %sys    %wio   %idle
08:16:13       3       5       0      92
08:16:16       3       5       0      92
08:16:19       2       6       0      92
08:16:22       2       4       0      94
08:16:25       2       4       0      93

Average        2       5       0      93

磁盘IO使用率较高

 

QUOTE:
iostat -cxn 5
                 extended device statistics              
    r/s    w/s   kr/s   kw/s wait actv wsvc_t asvc_t  %w  %b device
    0.0    0.0    0.0    0.0  0.0  0.0    0.0    0.0   0   0 d20
    0.0    0.0    0.0    0.0  0.0  0.0    0.0    0.0   0   0 d21
    0.0    0.0    0.0    0.0  0.0  0.0    0.0    0.0   0   0 d22
    0.0    0.6    0.0    0.4  0.0  0.0    0.0    9.1   0   0 c1t0d0
   18.6  128.2   70.8 1440.9  0.0  3.8    0.0   25.9   0  81 c1t1d0

内存使用及机器负荷

 

QUOTE:
prstat
PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP      
   279 root     1577M 1573M cpu1     0    0   3:45:19 3.7% squid/1
   125 named      10M 7752K sleep   59    0   0:04:56 0.1% named/11
   280 nobody   1168K  840K sleep   60    0   0:04:15 0.1% unlinkd/1

Total: 26 processes, 134 lwps, load averages: 0.50, 0.55, 0.54

squid的信息

 

QUOTE:
squidclient -p 8081 mgr:info

HTTP/1.0 200 OK
Server: squid/2.6.STABLE10
Date: Wed, 21 Mar 2007 00:23:01 GMT
Content-Type: text/plain
Expires: Wed, 21 Mar 2007 00:23:01 GMT
Last-Modified: Wed, 21 Mar 2007 00:23:01 GMT
X-Cache: MISS from none
Via: 1.0 none:8081 (squid/2.6.STABLE10)
Proxy-Connection: close

Squid Object Cache: Version 2.6.STABLE10
Start Time:     Tue, 20 Mar 2007 04:32:03 GMT
Current Time:   Wed, 21 Mar 2007 00:23:01 GMT
Connection information for squid:
        Number of clients accessing cache:      4514
        Number of HTTP requests received:       7291534
        Number of ICP messages received:        0
        Number of ICP messages sent:    0
        Number of queued ICP replies:   0
        Request failure ratio:   0.00
        Average HTTP requests per minute since start:   6122.4
        Average ICP messages per minute since start:    0.0
        Select loop called: 39501660 times, 1.809 ms avg
Cache information for squid:
        Request Hit Ratios:     5min: 46.8%, 60min: 47.8%
        Byte Hit Ratios:        5min: 14.7%, 60min: 14.5%
        Request Memory Hit Ratios:      5min: 17.4%, 60min: 21.3%
        Request Disk Hit Ratios:        5min: 13.4%, 60min: 11.9%
        Storage Swap size:      24968613 KB
        Storage Mem size:       1048296 KB
        Mean Object Size:       22.17 KB
        Requests given to unlinkd:      871980
Median Service Times (seconds)  5 min    60 min:
        HTTP Requests (All):   0.19742  0.12106
        Cache Misses:          0.44492  0.30459
        Cache Hits:            0.07014  0.04277
        Near Hits:             0.30459  0.22004
        Not-Modified Replies:  0.05046  0.03427
        DNS Lookups:           0.04854  0.02809
        ICP Queries:           0.00000  0.00000
Resource usage for squid:
        UP Time:        71457.499 seconds
        CPU Time:       13602.398 seconds
        CPU Usage:      19.04%
        CPU Usage, 5 minute avg:        30.82%
        CPU Usage, 60 minute avg:       30.37%
        Process Data Segment Size via sbrk(): 1596379 KB
        Maximum Resident Size: 0 KB
        Page faults with physical i/o: 10096743
Memory usage for squid via mallinfo():
        Total space in arena:  1596379 KB
        Ordinary blocks:       1471660 KB 258638 blks
        Small blocks:               0 KB      0 blks
        Holding blocks:         10928 KB     10 blks
        Free Small blocks:          0 KB
        Free Ordinary blocks:  124718 KB
        Total in use:          1482588 KB 92%
        Total free:            124718 KB 8%
        Total size:            1607307 KB
Memory accounted for:
        Total accounted:       1287875 KB
        memPoolAlloc calls: 753300395
        memPoolFree calls: 746272417
File descriptor usage for squid:
        Maximum number of file descriptors:   32768
        Largest file desc currently in use:   5321
        Number of file desc currently in use: 4396
        Files queued for open:                   0
        Available number of file descriptors: 28372
        Reserved number of file descriptors:   100
        Store Disk files open:                  26
        IO loop method:                     poll
Internal Data Structures:
        1133385 StoreEntries
        143938 StoreEntries with MemObjects
        143638 Hot Object Cache Items
        1126459 on-disk objects

发表在 article | 标签为 | squid负载过高,必然DOWN机,垦请高手来分析已关闭评论