FreeBSD 使用手冊

FreeBSD 文件計畫

修訂: 47472

Copyright

Redistribution and use in source (XML DocBook) and 'compiled' forms (XML, HTML, PDF, PostScript, RTF and so forth) with or without modification, are permitted provided that the following conditions are met:

  1. Redistributions of source code (XML DocBook) must retain the above copyright notice, this list of conditions and the following disclaimer as the first lines of this file unmodified.

  2. Redistributions in compiled form (transformed to other DTDs, converted to PDF, PostScript, RTF and other formats) must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

重要:

THIS DOCUMENTATION IS PROVIDED BY THE FREEBSD DOCUMENTATION PROJECT "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FREEBSD DOCUMENTATION PROJECT BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS DOCUMENTATION, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

FreeBSD 是 FreeBSD基金會的註冊商標

3Com 和 HomeConnect 是 3Com Corporation 的註冊商標。

3ware 和 Escalade 是 3ware Inc 的註冊商標。

ARM 是 ARM Limited. 的註冊商標。

Adaptec 是 Adaptec, Inc. 的註冊商標。

Adobe, Acrobat, Acrobat Reader, 以及 PostScript 是 Adobe Systems Incorporated 在美國和/或其他國家的商標或註冊商標。

Apple, AirPort, FireWire, Mac, Macintosh, Mac OS, Quicktime, 以及 TrueType 是 Apple Computer, Inc. 在美國以及其他國家的註冊商標。

Sound Blaster 是 Creative Technology Ltd. 在美國和/或其他國家的註冊商標。

Android is a trademark of Google Inc.

Heidelberg, Helvetica, Palatino, 和 Times Roman 是 Heidelberger Druckmaschinen AG 在美國以及其他國家的商標或註冊商標。

IBM, AIX, OS/2, PowerPC, PS/2, S/390, 和 ThinkPad 是 國際商用機器公司在美國和其他國家的註冊商標或商標。

IEEE, POSIX, 和 802 是 Institute of Electrical and Electronics Engineers, Inc. 在美國的註冊商標。

Intel, Celeron, EtherExpress, i386, i486, Itanium, Pentium, 和 Xeon 是 Intel Corporation 及其分支機構在美國和其他國家的商標或註冊商標。

Intuit 和 Quicken 是 Intuit Inc., 或其子公司在美國和其他國家的商標或註冊商標。

Linux 是 Linus Torvalds 的註冊商標。

LSI Logic, AcceleRAID, eXtremeRAID, MegaRAID 和 Mylex 是 LSI Logic Corp 的商標或註冊商標。

Microsoft, IntelliMouse, MS-DOS, Outlook, Windows, Windows Media, 和 Windows NT 是 Microsoft Corporation 在美國和/或其他國家的商標或註冊商標。

Motif, OSF/1, 和 UNIX 是 The Open Group 在美國和其他國家的註冊商標; IT DialTone 和 The Open Group 是其商標。

Oracle 是 Oracle Corporation 的註冊商標。

RealNetworks, RealPlayer, 和 RealAudio 是 RealNetworks, Inc. 的註冊商標。

Red Hat, RPM, 是 Red Hat, Inc. 在美國和其他國家的註冊商標。

Sun, Sun Microsystems, Java, Java Virtual Machine, JDK, JSP, JVM, Netra, Solaris, StarOffice 和 SunOS 是 Sun Microsystems, Inc. 在美國和其他國家的商標或註冊商標。

MATLAB 是 The MathWorks, Inc. 的註冊商標。

SpeedTouch 是 Thomson 的商標。

U.S. Robotics 和 Sportster 是 U.S. Robotics Corporation 的註冊商標。

VMware 是 VMware, Inc. 的商標

Waterloo Maple 和 Maple 是 Waterloo Maple Inc 的商標或註冊商標

Mathematica 是 Wolfram Research, Inc 的註冊商標。

XFree86 是 The XFree86 Project, Inc 的商標。.

Ogg Vorbis 和 Xiph.Org 是 Xiph.Org 的商標。

許多製造商和經銷商使用一些稱為商標的圖案或文字設計來彰顯自己的產品。 本文中出現的眾多商標,以及 FreeBSD Project 本身廣所人知的商標,後面將以 '™' 或 '®' 符號來標註。

2015-10-01 由 delphij.
摘要

歡迎使用FreeBSD! 本使用手冊涵蓋範圍包括了 FreeBSD 8.4-RELEASEFreeBSD 9.3-RELEASEFreeBSD 10.2-RELEASE 的安裝和日常使用。 這份使用手冊是很多人的集體創作,而且仍然『持續不斷』的進行中。 許多章節仍未完成,已完成的部份也有些需要更新。 如果您有興趣協助本計畫的話,請寄 e-mail 到 FreeBSD documentation project 郵遞論壇。 在 FreeBSD 網站 可以找到這份文件的最新版本(舊版文件可從 http://docs.FreeBSD.org/doc/ 取得),也可以從 FreeBSD FTP 伺服器 或是眾多 mirror 站臺 下載不同格式的資料。 如果比較偏好實體書面資料,那可以在 FreeBSD Mall 購買。 此外,也可以在 使用手冊 中搜尋資料。

[ 章節模式 / 完整模式 ]

內容目錄
I. 開始使用 FreeBSD
1. 簡介
1.1. 概述
1.2. Welcome to FreeBSD!
1.3. 關於 FreeBSD 計劃
2. 安裝 FreeBSD 9.X 和更新的版本
2.1. 概述
2.2. 最低硬體需求
2.3. 安裝前的工作
2.4. 開始安裝
2.5. 使用 bsdinstall
2.6. 配置磁碟空間
2.7. Committing to the Installation
2.8. Post-Installation
2.9. 故障排除
2.10. 使用 Live CD
3. UNIX 基礎概念
3.1. 概述
3.2. Virtual Consoles 和終端機
3.3. Users and Basic Account Management
3.4. 權限
3.5. 目錄結構
3.6. 磁碟組織
3.7. 掛載與卸載檔案系統
3.8. 程序
3.9. Daemon、信號及終止程序
3.10. Shells
3.11. 文字編輯器
3.12. 設備及設備節點
3.13. 更多資訊
4. 軟體套件管理篇:Packages 及 Ports 機制
4.1. 概述
4.2. 安裝軟體的各種方式介紹
4.3. 尋找想裝的軟體
4.4. Using pkg for Binary Package Management
4.5. 使用 Ports 管理機制
4.6. 安裝之後,有什麼後續注意事項嗎?
4.7. 如何處理爛掉(Broken)的 Ports?
5. X Window 視窗系統
5.1. 概述
5.2. 瞭解 X 的世界
5.3. 安裝 X11
5.4. 設定 X11
5.5. 在 X11 中使用字型
5.6. The X Display Manager
5.7. 桌面環境
II. 一般性工作
6. 桌面環境應用程式
6.1. 概述
6.2. 瀏覽器
6.3. 辦公室軟體
6.4. 文件閱覽器
6.5. 財務
6.6. 摘要
7. 多媒體影音娛樂(Multimedia)
7.1. 概述
7.2. 設定音效卡
7.3. MP3 音樂
7.4. 播放影片
7.5. 設定電視卡(TV Cards)
7.6. 掃描器
8. 設定 FreeBSD Kernel
8.1. 概述
8.2. 為何需要重新調配、編譯 kernel?
8.3. 探測系統硬體
8.4. 重新調配、編譯 kernel
8.5. kernel 設定檔解說
8.6. If Something Goes Wrong
9. 列印
9.1. 概述
9.2. 介紹
9.3. 基礎設定
9.4. Advanced Printer Setup
9.5. Using Printers
9.6. Alternatives to the Standard Spooler
9.7. Troubleshooting
10. Linux® 二進位檔的相容性
10.1. 概述
10.2. 設置 Linux® 二進位檔相容性
10.3. 進階主題
III. 系統管理
11. 設定與效能調校(Tuning)
11.1. 概述
11.2. 最主要的設定檔
11.3. 各式應用程式的設定檔
11.4. 各種 Services 的啟動方式
11.5. 設定 cron
11.6. 在 FreeBSD 使用 rc
11.7. 設定網路卡
11.8. 虛擬主機(Virtual Hosts)
11.9. 還有哪些主要設定檔呢?
11.10. Tuning with sysctl
11.11. Tuning Disks
11.12. Tuning Kernel Limits
11.13. Adding Swap Space
11.14. Power and Resource Management
11.15. Using and Debugging FreeBSD ACPI
12. FreeBSD 開機流程篇
12.1. 概述
12.2. Booting 問題
12.3. The Boot Manager and Boot Stages
12.4. Kernel Interaction During Boot
12.5. Device Hints
12.6. Init: Process Control Initialization
12.7. Shutdown Sequence
13. 系統安全
13.1. 概述
13.2. Introduction
13.3. One-time Passwords
13.4. TCP Wrapper
13.5. Kerberos
13.6. OpenSSL
13.7. VPN over IPsec
13.8. OpenSSH
13.9. Access Control Lists
13.10. Monitoring Third Party Security Issues
13.11. FreeBSD Security Advisories
13.12. Process Accounting
13.13. Resource Limits
14. Jails
14.1. 概述
14.2. Jail 相關術語
14.3. 背景故事
14.4. 建立和控制 Jail
14.5. 微調與管理
14.6. Jail 的應用
15. Mandatory Access Control
15.1. Synopsis
15.2. Key Terms in this Chapter
15.3. Explanation of MAC
15.4. Understanding MAC Labels
15.5. Module Configuration
15.6. The MAC bsdextended Module
15.7. The MAC ifoff Module
15.8. The MAC portacl Module
15.9. MAC Policies with Labeling Features
15.10. The MAC partition Module
15.11. The MAC Multi-Level Security Module
15.12. The MAC Biba Module
15.13. The MAC LOMAC Module
15.14. Implementing a Secure Environment with MAC
15.15. Another Example: Using MAC to Constrain a Web Server
15.16. Troubleshooting the MAC Framework
16. Security Event Auditing
16.1. Synopsis
16.2. Key Terms - Words to Know
16.3. Installing Audit Support
16.4. Audit Configuration
16.5. Event Audit Administration
17. 儲存設備篇
17.1. 概述
17.2. 裝置名稱
17.3. 新增磁碟
17.4. Resizing and Growing Disks
17.5. USB 儲存裝置
17.6. Creating and Using CD Media
17.7. Creating and Using DVD Media
17.8. Creating and Using Floppy Disks
17.9. Backup Basics
17.10. Memory Disks
17.11. File System Snapshots
17.12. 磁碟空間配額(Quota)
17.13. Encrypting Disk Partitions
17.14. Encrypting Swap
17.15. Highly Available Storage (HAST)
18. GEOM: Modular Disk Transformation Framework
18.1. 概述
18.2. RAID0 - 分散連結(striping)
18.3. RAID1 - 鏡射(Mirroring)
18.4. RAID3 - Byte-level Striping with Dedicated Parity
18.5. Software RAID Devices
18.6. GEOM Gate Network
18.7. Labeling Disk Devices
18.8. UFS Journaling Through GEOM
19. The Z File System (ZFS)
19.1. What Makes ZFS Different
19.2. Quick Start Guide
19.3. zpool Administration
19.4. zfs Administration
19.5. Delegated Administration
19.6. Advanced Topics
19.7. Additional Resources
19.8. ZFS Features and Terminology
20. Other File Systems
20.1. Synopsis
20.2. Linux® File Systems
21. Virtualization(虛擬機器)
21.1. Synopsis
21.2. 安裝 FreeBSD 為 Guest OS
21.3. 以 FreeBSD 為 Host OS
22. 語系設定 - I18N/L10N 用法與設定
22.1. 概述
22.2. L10N 基礎概念
22.3. 使用語系設定(Localization)
22.4. Compiling I18N Programs
22.5. Localizing FreeBSD to Specific Languages
23. 更新、升級 FreeBSD
23.1. 概述
23.2. FreeBSD Update
23.3. 更新文件組
23.4. 追蹤發展分支
23.5. 同步原始碼
23.6. 重新編譯 World
23.7. 追蹤多追蹤多部機器
24. DTrace
24.1. Synopsis
24.2. Implementation Differences
24.3. Enabling DTrace Support
24.4. Using DTrace
IV. 網路通訊
25. Serial Communications
25.1. Synopsis
25.2. Introduction
25.3. Terminals
25.4. Dial-in Service
25.5. Dial-out Service
25.6. Setting Up the Serial Console
26. PPP and SLIP
26.1. Synopsis
26.2. Using User PPP
26.3. Using Kernel PPP
26.4. Troubleshooting PPP Connections
26.5. Using PPP over Ethernet (PPPoE)
26.6. Using PPP over ATM (PPPoA)
26.7. Using SLIP
27. 電子郵件
27.1. 概述
27.2. 使用電子郵件
27.3. sendmail Configuration
27.4. Changing Your Mail Transfer Agent
27.5. Troubleshooting
27.6. Advanced Topics
27.7. SMTP with UUCP
27.8. Setting Up to Send Only
27.9. Using Mail with a Dialup Connection
27.10. SMTP Authentication
27.11. Mail User Agents
27.12. Using fetchmail
27.13. Using procmail
28. 網路伺服器
28.1. 概述
28.2. The inetd Super-Server
28.3. Network File System (NFS)
28.4. Network Information System (NIS)
28.5. Lightweight Directory Access Protocol (LDAP)
28.6. Dynamic Host Configuration Protocol (DHCP)
28.7. Domain Name System (DNS)
28.8. Apache HTTP Server
28.9. File Transfer Protocol (FTP)
28.10. File and Print Services for Microsoft® Windows® Clients (Samba)
28.11. Clock Synchronization with NTP
28.12. iSCSI Initiator and Target Configuration
29. 防火牆
29.1. 概述
29.2. 淺談防火牆概念
29.3. 防火牆相關軟體
29.4. OpenBSD 封包過濾器 (Packet Filter, PF)及 ALTQ
29.5. IPFILTER (IPF) 防火牆
29.6. IPFW
30. 網路進階練功房
30.1. 概述
30.2. Gateways and Routes
30.3. Wireless Networking
30.4. Bluetooth
30.5. Bridging
30.6. Link Aggregation and Failover
30.7. Diskless Operation
30.8. ISDN
30.9. Network Address Translation
30.10. Parallel Line IP (PLIP)
30.11. IPv6
30.12. Asynchronous Transfer Mode (ATM)
30.13. Common Access Redundancy Protocol (CARP)
V. 附錄
A. 取得 FreeBSD 的方式
A.1. CDDVD 合集
A.2. FTP
A.3. Using CTM
A.4. Using Subversion
A.5. Using rsync
B. 參考文獻
B.1. FreeBSD 相關的書籍、雜誌
B.2. 使用說明手冊
B.3. 系統管理指南
B.4. 程式設計師指南
B.5. 深入作業系統
B.6. 資安領域的參考文獻
B.7. 硬體方面的參考文獻
B.8. UNIX® 歷史淵源
B.9. 雜誌、期刊
C. 網際網路上的資源
C.1. 郵遞論壇(Mailing Lists)
C.2. Usenet Newsgroups
C.3. World Wide Web Servers
C.4. Email Addresses
C.5. Shell Accounts
D. PGP Keys
D.1. Officers
D.2. Core Team Members
D.3. Developers
FreeBSD Glossary
索引
附圖目錄
2.1. FreeBSD 開機管理程式選單
2.2. FreeBSD 開機選項選單
2.3. 歡迎選單
2.4. Keymap Selection
2.5. 選擇鍵盤選單
2.6. Enhanced Keymap Menu
2.7. 設定主機名稱
2.8. 選擇要安裝的組件
2.9. 從網路安裝
2.10. 選擇鏡像站
2.11. Partitioning Choices on FreeBSD 9.x
2.12. Partitioning Choices on FreeBSD 10.x and Higher
2.13. Selecting from Multiple Disks
2.14. Selecting Entire Disk or Partition
2.15. Review Created Partitions
2.16. Manually Create Partitions
2.17. Manually Create Partitions
2.18. Manually Create Partitions
2.19. ZFS Partitioning Menu
2.20. ZFS Pool Type
2.21. Disk Selection
2.22. Invalid Selection
2.23. Analysing a Disk
2.24. Disk Encryption Password
2.25. Last Chance
2.26. Final Confirmation
2.27. Fetching Distribution Files
2.28. Verifying Distribution Files
2.29. Extracting Distribution Files
2.30. Setting the root Password
2.31. Choose a Network Interface
2.32. Scanning for Wireless Access Points
2.33. Choosing a Wireless Network
2.34. WPA2 Setup
2.35. Choose IPv4 Networking
2.36. Choose IPv4 DHCP Configuration
2.37. IPv4 Static Configuration
2.38. Choose IPv6 Networking
2.39. Choose IPv6 SLAAC Configuration
2.40. IPv6 Static Configuration
2.41. DNS Configuration
2.42. Select Local or UTC Clock
2.43. 選擇區域
2.44. 選擇國家
2.45. 選擇時區
2.46. 確認時區
2.47. Selecting Additional Services to Enable
2.48. Enabling Crash Dumps
2.49. 加入使用者帳號
2.50. 輸入使用者資訊
2.51. 離開使用者和群組管理
2.52. 最後設定
2.53. Manual Configuration
2.54. Complete the Installation
附表目錄
2.1. Partitioning Schemes
3.1. Utilities for Managing User Accounts
3.2. 磁碟機代號
13.1. Login Class Resource Limits
17.1. 命名規則
25.1. DB-25 to DB-25 Null-Modem Cable
25.2. DB-9 to DB-9 Null-Modem Cable
25.3. DB-9 to DB-25 Null-Modem Cable
25.4. Signal Names
28.1. NIS Terminology
28.2. Additional Users
28.3. Additional Systems
28.4. DNS Terminology
30.1. Wiring a Parallel Cable for Networking
30.2. Reserved IPv6 addresses
範例目錄
2.1. Creating Traditional Split File System Partitions
3.1. Install a Program As the Superuser
3.2. Adding a User on FreeBSD
3.3. rmuser Interactive Account Removal
3.4. Using chpass as Superuser
3.5. Using chpass as Regular User
3.6. Changing Your Password
3.7. Changing Another User's Password as the Superuser
3.8. Adding a Group Using pw(8)
3.9. Adding User Accounts to a New Group Using pw(8)
3.10. Adding a New Member to a Group Using pw(8)
3.11. Using id(1) to Determine Group Membership
3.12. 磁碟、slice 及分割區命名範例
3.13. 磁碟的概念模型
11.1. Creating a Swapfile on FreeBSD
12.1. boot0 Screenshot
12.2. boot2 Screenshot
12.3. An Insecure Console in /etc/ttys
13.1. Create a Secure Tunnel for SMTP
13.2. Secure Access of a POP3 Server
13.3. Bypassing a Firewall
17.1. Using dump over ssh
17.2. Using dump over ssh with RSH Set
17.3. Backing Up the Current Directory with tar
17.4. Restoring Up the Current Directory with tar
17.5. Usingls and cpio to Make a Recursive Backup of the Current Directory
17.6. Backing Up the Current Directory with pax
18.1. Labeling Partitions on the Boot Disk
25.1. Adding Terminal Entries to /etc/ttys
27.1. Configuring the sendmail Access Database
27.2. Mail Aliases
27.3. Example Virtual Domain Mail Map
28.1. Reloading the inetd Configuration File
28.2. Mounting an Export with amd
28.3. Mounting an Export with autofs(5)
28.4. Sample /etc/ntp.conf
30.1. LACP aggregation with a Cisco switch
30.2. Failover mode
30.3. Branch Office or Home Network
30.4. Head Office or Other LAN

給讀者的話

若您是第一次接觸 FreeBSD 的新手,可以在本書第一部分找到 FreeBSD 的安裝方法,同時會逐步介紹 UNIX® 的基礎概念與一些常用、共通的東西。而閱讀這部分並不難,只需要您有探索的精神和接受新概念。

讀完這些之後,手冊中的第二部分花很長篇幅介紹的各種廣泛主題,相當值得系統管理者去注意。 在閱讀這些章節的內容時所需要的背景知識,都註釋在該章的大綱裡面,若不熟的話,可在閱讀前先預習一番。

延伸閱讀方面,可參閱 附錄 B, 參考文獻

第三版的主要修訂

您目前看到的這本手冊第三版是 FreeBSD 文件計劃的成員歷時兩年完成的心血之作。 新版的主要修訂部分,如下:

  • 章 11, 設定與效能調校(Tuning), 設定與效能調校(Tuning),該章節針對新內容作更新,比如: ACPI 電源管理、cron、以及其他更多的 kernel tuning 選項說明內容。

  • 章 13, 系統安全, 系統安全篇,該章節增加了虛擬私人網路(VPN)、檔案系統的存取控制(ACL),以及安全公告(Security Advisories)的內容。

  • 章 15, Mandatory Access Control, 集權式存取控制(MAC)是本版所增加的章節。本章介紹:什麼是 MAC 機制?以及如何運用它來使您的 FreeBSD 系統更安全。

  • 章 17, 儲存設備篇, 儲存設備篇,新增了像是:USB 隨身碟、檔案系統快照(snapshot)、檔案系統配額(quota) 、檔案及網路的備援檔案系統、以及如何對硬碟分割區作加密等詳解。

  • 章 26, PPP and SLIPPPP 及 SLIP 一章中增加了故障排除的說明。

  • 章 27, 電子郵件電子郵件一章中新增有關如何使用其它的 MTA 程式、SMTP 認証、UUCP、fecthmail、procmail 的運用以及其它進階專題。

  • 章 28, 網路伺服器, 網路伺服器篇,是新版中全新的一章。這一章介紹了如何架設 Apache HTTP 伺服器、FTPd,以及用於支援 Microsoft Windows client 的 Samba 伺服器。其中有些段落來自原先的章 30, 網路進階練功房進階網路應用一章。

  • 章 30, 網路進階練功房進階網路應用一章新增有關在 FreeBSD 中使用藍芽設備、安裝無線網路以及使用 ATM(Asynchronous Transfer Mode) 網路的介紹。

  • 增加了一份詞彙表(Glossary),用以說明全書中出現的術語。

  • 重新美編書中所列的圖表。

第二版的主要修訂

本手冊的第二版是 FreeBSD 文件計劃的成員歷時兩年完成的心血之作。第二版包含了如下的主要變動︰

本書架構

本書主要分為五大部分,第一部份『開始使用』:介紹 FreeBSD 的安裝、基本操作。 讀者可根據自己的程度,循序或者跳過一些熟悉的主題來閱讀; 第二部分『常用操作』:介紹 FreeBSD 常用功能,這部分可以不按順序來讀。 每章前面都會有概述,概述會描述本章節涵蓋的內容和讀者應該已知的, 這主要是讓讀者可以挑喜歡的章節閱讀; 第三部分『系統管理』:介紹 FreeBSD 老手所感興趣的各種專題部分; 第四部分『網路通訊』:則包括網路和各式 Server 專題;而第五部分『附錄』:是各種有關 FreeBSD 的資源。

章 1, 簡介, 簡介篇

向新手介紹 FreeBSD。該篇說明了 FreeBSD 計劃的歷史、目標和開發模式。

章 3, UNIX 基礎概念, UNIX® 基礎概念篇

Covers the basic commands and functionality of the FreeBSD operating system. If you are familiar with Linux® or another flavor of UNIX® then you can probably skip this chapter.

章 4, 軟體套件管理篇:Packages 及 Ports 機制, 軟體套件管理篇

Covers the installation of third-party software with both FreeBSD's innovative Ports Collection and standard binary packages.

章 5, X Window 視窗系統, X Window 視窗系統篇

Describes the X Window System in general and using X11 on FreeBSD in particular. Also describes common desktop environments such as KDE and GNOME.

章 6, 桌面環境應用程式, Desktop Applications

Lists some common desktop applications, such as web browsers and productivity suites, and describes how to install them on FreeBSD.

章 7, 多媒體影音娛樂(Multimedia), Multimedia

Shows how to set up sound and video playback support for your system. Also describes some sample audio and video applications.

章 8, 設定 FreeBSD Kernel, Configuring the FreeBSD Kernel

Explains why you might need to configure a new kernel and provides detailed instructions for configuring, building, and installing a custom kernel.

章 9, 列印, 列印篇

Describes managing printers on FreeBSD, including information about banner pages, printer accounting, and initial setup.

章 10, Linux® 二進位檔的相容性, Linux® Binary Compatibility

Describes the Linux® compatibility features of FreeBSD. Also provides detailed installation instructions for many popular Linux® applications such as Oracle®, SAP® R/3®, and Mathematica®.

章 11, 設定與效能調校(Tuning)

Describes the parameters available for system administrators to tune a FreeBSD system for optimum performance. Also describes the various configuration files used in FreeBSD and where to find them.

章 12, FreeBSD 開機流程篇

Describes the FreeBSD boot process and explains how to control this process with configuration options.

章 13, 系統安全

Describes many different tools available to help keep your FreeBSD system secure, including Kerberos, IPsec and OpenSSH.

章 14, Jails

Describes the jails framework, and the improvements of jails over the traditional chroot support of FreeBSD.

章 15, Mandatory Access Control

Explains what Mandatory Access Control (MAC) is and how this mechanism can be used to secure a FreeBSD system.

章 16, Security Event Auditing

Describes what FreeBSD Event Auditing is, how it can be installed, configured, and how audit trails can be inspected or monitored.

章 17, 儲存設備篇

Describes how to manage storage media and filesystems with FreeBSD. This includes physical disks, RAID arrays, optical and tape media, memory-backed disks, and network filesystems.

章 18, GEOM: Modular Disk Transformation Framework

Describes what the GEOM framework in FreeBSD is and how to configure various supported RAID levels.

章 20, Other File Systems

Examines support of non-native file systems in FreeBSD, like the Z File System from Sun™.

章 21, Virtualization(虛擬機器)

Describes what virtualization systems offer, and how they can be used with FreeBSD.

章 22, 語系設定 - I18N/L10N 用法與設定

Describes how to use FreeBSD in languages other than English. Covers both system and application level localization.

章 23, 更新、升級 FreeBSD

Explains the differences between FreeBSD-STABLE, FreeBSD-CURRENT, and FreeBSD releases. Describes which users would benefit from tracking a development system and outlines that process. Covers the methods users may take to update their system to the latest security release.

章 24, DTrace

Describes how to configure and use the DTrace tool from Sun™ in FreeBSD. Dynamic tracing can help locate performance issues, by performing real time system analysis.

章 25, Serial Communications, Serial Communications

Explains how to connect terminals and modems to your FreeBSD system for both dial in and dial out connections.

章 26, PPP and SLIP, PPP and SLIP

Describes how to use PPP, SLIP, or PPP over Ethernet to connect to remote systems with FreeBSD.

章 27, 電子郵件, Electronic Mail

Explains the different components of an email server and dives into simple configuration topics for the most popular mail server software: sendmail.

章 28, 網路伺服器, Network Servers

Provides detailed instructions and example configuration files to set up your FreeBSD machine as a network filesystem server, domain name server, network information system server, or time synchronization server.

章 29, 防火牆, Firewalls

Explains the philosophy behind software-based firewalls and provides detailed information about the configuration of the different firewalls available for FreeBSD.

章 30, 網路進階練功房, Advanced Networking

Describes many networking topics, including sharing an Internet connection with other computers on your LAN, advanced routing topics, wireless networking, bluetooth, ATM, IPv6, and much more.

附錄 A, 取得 FreeBSD 的方式, Obtaining FreeBSD

Lists different sources for obtaining FreeBSD media on CDROM or DVD as well as different sites on the Internet that allow you to download and install FreeBSD.

附錄 B, 參考文獻, Bibliography

This book touches on many different subjects that may leave you hungry for a more detailed explanation. The bibliography lists many excellent books that are referenced in the text.

附錄 C, 網際網路上的資源, Resources on the Internet

Describes the many forums available for FreeBSD users to post questions and engage in technical conversations about FreeBSD.

附錄 D, PGP Keys, PGP Keys

Lists the PGP fingerprints of several FreeBSD Developers.

本書的編排體裁

為方便閱讀本書,以下是一些本書所遵循的編排體裁:

文字編排體裁

斜體字(Italic)

斜體字型(Italic) 用於:檔名、目錄、網址(URL)、 強調語氣、以及第一次提及的技術詞彙。

定寬字(Monospace)

定寬字(Monospace) 用於: 錯誤訊息、指令、環境變數、port 名稱、主機名稱(hostname)、帳號、群組、設備(device)名稱、變數、 程式碼等。

粗體字型(Bold)

粗體字表示:應用程式、命令、按鍵。

使用者輸入

鍵盤輸入以 粗體字(Bold) 表示,以便與一般文字做區隔。 組合鍵是指同時按下一些按鍵,我們以 `+' 來表示連接,像是:

Ctrl+Alt+Del

也就是說,一起按 Ctrl 鍵、 Alt 鍵,以及 Del 鍵。

若要逐一按鍵,那麼會以逗號(,)來表示,像是:

Ctrl+X, Ctrl+S

也就是說:先同時按下 CtrlX 鍵, 然後放開後再同時按 CtrlS 鍵。

舉個實例

下面例子以 E:\> 為開頭的代表 MS-DOS® 指令部分。 若沒有特殊情況的話,這些指令應該是在 Microsoft® Windows® 環境的 命令提示字元(Command Prompt) 內執行。

E:\> tools\fdimage floppies\kern.flp A:

例子若是先以 # 為開頭再接指令的話,就是指在 FreeBSD 中以 root 權限來下命令。 你可以先以 root登入系統並下指令,或是以你自己的帳號登入,並使用 su(1) 來取得 root 權限。

# dd if=kern.flp of=/dev/fd0

例子若是先以 % 為開頭再接指令的話,就是指在 FreeBSD 中以一般帳號來下命令即可。 除非有提到其他用法,否則都是預設為 C-shell(csh/tcsh) 語法,用來設定環境變數以及下其他指令的意思。

% top

致謝

您所看到的這本書是經過數百個分散在世界各地的人所努力而來的結果。 無論他們只是糾正一些錯誤或提交完整的章節,所有的點滴貢獻都是非常寶貴有用的。

也有一些公司透過提供資金讓作者專注於撰稿、提供出版資金等模式來支持文件的寫作。 其中,BSDi (之後併入 Wind River Systems) 資助 FreeBSD 文件計劃成員來專職改善這本書直到 2000 年 3 月第一版的出版。(ISBN 1-57176-241-8) Wind River Systems 同時資助其他作者來對輸出架構做很多改進,以及給文章增加一些附加章節。這項工作結束於 2001 年 11 月第二版。(ISBN 1-57176-303-1) 在 2003-2004 兩年中,FreeBSD Mall 把報酬支付給改進這本手冊以使第三版印刷版本能夠出版的志工。

部 I. 開始使用 FreeBSD

這部份是提供給初次使用 FreeBSD 的使用者和系統管理者。 這些章節包括:

  • 介紹 FreeBSD 給您。

  • 在安裝過程給您指引。

  • 教您 UNIX® 的基礎及原理。

  • 展示給您看如何安裝豐富的 FreeBSD 的應用軟體

  • 向您介紹 X, UNIX® 的視窗系統以及詳細的桌面環境設定,讓您更有生產力。

我們試著儘可能的讓這段文字的參考連結數目降到最低,讓您在讀使用手冊的這部份時可以不太需要常常前後翻頁。

章 1. 簡介

Restructured, reorganized, and parts rewritten by Jim Mock.

1.1. 概述

非常感謝您對 FreeBSD 感興趣!以下章節涵蓋 FreeBSD 計劃的各方面:比如它的歷史、目標、開發模式等等。

讀完這章,您將了解︰

  • FreeBSD 與其他 OS 之間的關係;

  • FreeBSD 計劃的歷史源流;

  • FreeBSD 計劃的目標;

  • FreeBSD open-source 開發模式的基礎概念;

  • 當然囉,還有 FreeBSD 這名字的由來。

1.2. Welcome to FreeBSD!

FreeBSD 是一個從 4.4BSD-Lite 衍生出而能在以 Intel (x86 and Itanium®), AMD64, Alpha™, Sun UltraSPARC® 為基礎的電腦上執行的作業系統。同時,移植到其他平台的工作也在進行中。 對於本計劃歷史的介紹,請看 FreeBSD 歷史源流, 對於 FreeBSD 的最新版本介紹,請看 current release 。若打算對於 FreeBSD 計劃有所貢獻的話(像是程式碼硬體設備、基金), 請看 如何對 FreeBSD 有貢獻

1.2.1. FreeBSD 能做什麼?

FreeBSD 提供給你許多先進功能。這些功能包括:

  • 動態優先權調整的『先佔式多工』能夠確保,即使在系統負擔很重的情況下, 程式執行平順並且應用程式與使用者公平地共享資源。

  • 『多人共用(multi-user)』代表著許多人可以同時使用一個 FreeBSD 系統來處理各自的事務。 系統的硬體周邊(如印表機及磁帶機)也可以讓所有的使用者適當地分享。 也可以針對各別使用者或一群使用者的系統資源,予以設限, 以保護系統不致被過度使用。

  • 好用的『TCP/IP 網路功能』可支援許多業界標準,比如: SCTP、DHCP、NFS、NIS、PPP、SLIP、IPSec、IPv6 的支援,也就是說 FreeBSD 可以容易地跟其他作業系統透過網路共同運作,或是當作企業的伺服器用途 ,例如提供遠端檔案共享(NFS)及電子郵件(email)等服務, 或是讓您的企業連上網際網路(Internet)並提供 WWW、FTP、 路由(routing)、及防火牆(firewall、security) 等必備服務。

  • 『記憶體保護(Memory protection)』能確保程式(或是使用者)不會互相干擾, 即使任何程式有不正常的運作,都不會影響其他程式的執行。

  • FreeBSD 是『32位元(32-bit)』的作業系統 (在 Alpha、Itanium®、 AMD64 及 UltraSPARC® 上則是『64位元(64-bit)』) — 打從一開始便是這樣設計的。

  • 業界標準的『X Window 系統』(X11R7)可以在常見的便宜 VGA 顯示卡/螢幕, 提供了圖形化的使用者介面(GUI),並且包括了完整的原始程式碼。

  • 能『直接執行』許多其他作業系統(比如: Linux、SCO、SVR4、BSDI 和 NetBSD) 的可執行檔。

  • 數以萬計的立即可以執行的應用程式,這些都可透過 FreeBSD 的『ports』及『packages』軟體管理機制來取得。 不再需要費心到網路上到處搜尋所需要的軟體。

  • 此外,網路上尚有可非常容易移植的數以萬計應用程式。 FreeBSD 的原始程式碼與許多常見的商業版 UNIX® 系統都相容, 所以大部分的程式都只需要很少的修改(或根本不用修改) ,就可以編譯執行。

  • 需要時才置換(demand paged) virtual memorymerged VM/buffer cache 的設計, 這點在系統中有用去大量記憶體的程式執行時,仍然有不錯的效率表現。

  • 支援 CPU 的對稱多工處理(SMP):可以支援多 CPU 的電腦系統。

  • 完全相容的 CC++ 以及 Fortran 的環境和其他開發工具。 以及其他許多可供進階研發的程式語言也收集在 ports 和 packages。

  • 整個系統都有『原始程式碼』, 這讓你對作業環境擁有最完全的掌握度。 既然能擁有完全開放的系統,何苦被特定封閉軟體所約束,任廠商擺佈呢?

  • 廣泛且豐富的『線上文件』。

  • 當然囉,還不止如此!

FreeBSD 系統乃是基於美國加州大學柏克萊分校的電腦系統研究群 (Computer Systems Research Group 也就是 CSRG) 所發行的 4.4BSD-Lite,以及基於 BSD 系統開發的優良傳統。 除了由 CSRG 所提供的高品質的成果, 為了提供可處理真正具負荷的工作, FreeBSD 計劃也投入了數千小時以上的細部調整, 以能獲得最好的執行效率以及系統的穩定度。 正當許多商業上的巨人正努力地希望能提供效能及穩定時, FreeBSD 已經具備這樣的特質 -- 就是現在

FreeBSD 的運用範圍無限,其實完全限制在你的想像力上。 從軟體的開發到工廠自動化,或是人造衛星上面的天線的方位角度的遠端控制; 這些功能若可以用商用的 Unix 產品來達成, 那麼極有可能使用 FreeBSD 也能辦到! FreeBSD 也受益於來自於全球各研究中心及大學所開發的數千個高品質的軟體 ,這些通常只需要花費很少的費用或根本就是免費的。 當然也有商業軟體,而且出現的數目是與日俱增。

由於每個人都可以取得 FreeBSD 的原始程式碼, 這個系統可以被調整而能執行任何原本完全無法想像的功能或計劃, 而對於從各廠商取得的作業系統通常沒有辦法這樣地被修改。 以下提供一些人們使用 FreeBSD 的例子:

  • 網路服務: FreeBSD 內建強勁的網路功能使它成為網路服務(如下例)的理想平台:

    • 檔案伺服器(FTP servers)

    • 全球資訊網伺服器(WWW servers) (標準的或更安全的 [SSL] 連線)

    • IPv4 及 IPv6 routing

    • 防火牆以及 NAT (IP masquerading) gateways。

    • 電子郵件伺服器(Electronic Mail servers)

    • 網路新聞伺服器(USENET News) 或是電子佈告欄系統(BBS)

    • 還有更多...

    有了 FreeBSD,您可以容易地先用便宜的 386 PC, 再逐步升級您的機器到四個 CPU 的 Xeon 並使用磁碟陣列(RAID)來滿足您企業運用上的需求。

  • 教育: 若您是資工相關領域的學生,再也沒有比使用 FreeBSD 能學到更多作業系統、計算機結構、及網路的方法了。 另外如果你想利用電腦來處理一些其他的 工作,還有一些如 CAD、 數學運算以及圖形處理軟體等可以免費地取得使用。

  • 研究:有了完整的原始程式碼,FreeBSD 是研究作業系統及電腦科學的極佳環境。 具有免費且自由取得特性的 FreeBSD 也使得一個分置兩地的合作計劃,不必擔心版權及系統開放性的問題, 而能自在的交流。

  • 網路: 你如果需要 router、Name Server (DNS) 或安全的防火牆(Firewall), FreeBSD 可以輕易的將你沒有用到的 386 或 486 PC 變身成為絕佳的伺服器,甚至具有過濾封包(packet-filter) 的功能。

  • X 視窗工作站: FreeBSD 是 X 終端機的良策,你可以使用免費的 X11 Server。 FreeBSD 不但可以充當遠端 X 程式終端機, 也可以執行本地的 X 程式而減輕大型工作站的負荷。 如果有一台中央伺服器的話,FreeBSD 甚至可以經由網路開機 (不需硬碟,也就是diskless) ,而變成更便宜且易於管理的工作站。

  • 軟體開發: 基本安裝的 FreeBSD 就包含了完整的程式開發工具,如 GNU C/C++ 編譯器及除錯器。

你可以經由燒錄 CD-ROM、DVD 或是從 FTP 站上抓回 FreeBSD -- 包括立即可執行的系統以及系統的完整程式碼。 詳情請參閱 附錄 A, 取得 FreeBSD 的方式 取得 FreeBSD。

1.2.2. 誰在用 FreeBSD?

許多 Internet 上的大型網站都是以 FreeBSD 作為它的作業系統,例如:

以及許多其他的網站。

1.3. 關於 FreeBSD 計劃

接下來講的是 FreeBSD 計劃的背景,包含歷史源流的簡介、計劃的目標,以及開發的模式。

1.3.1. FreeBSD 歷史源流的簡介

Contributed by Jordan Hubbard.

FreeBSD 計畫的想法是在 1993 年初所形成的, 那是源自於維護一組 『非官方 386BSD 的 patchkit(修正工具)』計劃的三個協調維護人 Nate Williams,Rod Grimes 和我(Jordan Hubbard)。

我們最初的目標是做出一份 386BSD 綜合修正的 snapshot 版,以便修正當時一堆 patchkit 都不容易解決的問題。有些人可能還記得早期的計劃名稱叫做 386BSD 0.5386BSD Interim 就是這個原因。

386BSD 是 Bill Jolitz 的作業系統,在當時就已有約一年的分裂討論。 當該修正工具 (patchkit) 日漸龐雜得令人不舒服,我們無異議地同意要作一些事了, 並決定提供一份臨時性的 淨化版(cleanup) 來幫助 Bill。 然而,由於 Bill Jolitz 忽然決定取消其對該計劃的認可,且沒有明確指出未來的打算, 所以該計劃便突然面臨斷炊危機。

不久我們便決定在即使沒有 Bill 的支持下,讓該計劃仍然繼續下去, 最後我們採用 David Greenman 丟銅板決定的名字,也就是『FreeBSD』。 在詢問了當時的一些使用者意見之後,就開始決定了最初的目標, 當該計劃開始實施一切就要成真時,一切就變得更清楚了。 我跟 Walnut Creek CD-ROM 討論發行 CD-ROM 這樣子不便上網的人就可以用比較簡單的方式取得 FreeBSD。 Walnut Creek CD-ROM 不只贊成以 CD-ROM 來發行 FreeBSD 的想法,同時提供了一台機器以及快速的網際網路的頻寬。 如果不是 Walnut Creek CD-ROM 幾乎是空前的信任這個剛開始還是完全默默無聞的計劃, 那麼很可能 FreeBSD 不會如此快速的成長到今日這樣的規模。

第一張以 CD-ROM (及網路)發行的 FreeBSD 1.0 是在 1993 年十二月。 該版本是基於由 U.C. Berkeley 以磁帶方式發行的 4.3BSD-Lite (Net/2)以及許多來自於 386BSD 和自由軟體基金會的軟體。對於第一次發行而言還算成功, 我們又接著於 1994 年 5 月發行了相當成功的 FreeBSD 1.1。

然而此後不久,另一個意外的風暴在 Novell 和 U.C. Berkeley 關於 Berkeley Net/2 磁帶之法律地位的訴訟確定之後形成。 U.C. Berkeley 接受大部份的 Net/2 的程式碼都是『侵佔來的』且是屬於 Novell 的財產 -- 事實上是當時不久前從 AT&T 取得的。 Berkeley 得到的是 Novell 對於 4.4BSD-Lite 的『祝福』,最後當 4.4BSD-Lite 終於發行之後,便不再是侵佔行為。 而所有現有 Net/2 使用者都被強烈建議更換新版本,這包括了 FreeBSD。 於是,我們被要求於 1994 年 6 月底前停止散佈基於 Net/2 的產品。在此前提之下,本計劃被允許在期限以前作最後一次發行,也就是 FreeBSD 1.1.5.1。

FreeBSD 便開始了這宛如『重新發明輪子』的艱鉅工作 -- 從全新的且不完整的 4.4BSD-Lite 重新整合。 這個 Lite 版本是不完整的,因為 Berkeley 的 CSRG 已經刪除了大量在建立一個可以開機執行的系統所需要的程式碼 (基於若干法律上的要求),且該版本在 Intel 平台的移植是非常不完整的。 直到 1994 年 11 月本計劃才完成了這個轉移, 同時在該年 12 月底以 CD-ROM 以及網路的形式發行了 FreeBSD 2.0。 雖然該份版本在當時有點匆促粗糙,但仍是富有意義的成功。 隨之於 1995 年 6 月又發行了更容易安裝,更好的 FreeBSD 2.0.5。

我們在 1996 年 8 月發行了 FreeBSD 2.1.5,在 ISP 和商業團體中非常流行。 隨後, 2.1-STABLE 分支的另一個版本應運而生,它就是在 1997 年 2 月發行 FreeBSD 2.1.7.1 ,同時也是 2.1-STABLE 分支的最後版。之後此分支便進入維護狀態, 僅僅提供安全性的加強和其他嚴重錯誤修補的維護(RELENG_2_1_0)。

1996 年 11 月 FreeBSD 2.2 從開發主軸分支 (-CURRENT) 出來成為 RELENG_2_2 分支。它的第一個完整版(2.2.1)於 1997 年 4 月發行。 2.2 分支的延續版本在 97 年夏秋之間發行的,其最後版是在 1998 年 11 月發行的 2.2.8 版。 第一個正式的 3.0 版本在 1998 年 10 月發行,亦即宣告 2.2 分支的落幕。

1999/01/20 日再度分支,這產生了 4.0-CURRENT 以及 3.X-STABLE 兩個分支。 3.X-STABLE 方面,3.1 發行於 1999/02/15,3.2 發行於1999/05/15,3.3 發行於 1999/09/16, 3.4 發行於 1999/12/20,3.5 發行於 2000/06/24 ,接下來幾天後發佈了一些的修補檔(對 Kerberos 安全性方面的修正),就升級至 3.5.1 ,這是 3.X 分支最後一個發行版本。

在 2000/03/13 又有了一個新的分支, 也就是 4.X-STABLE 。這個分支之後發佈了許多的發行版本︰ 4.0-RELEASE 在 2000 年 3 月發行, 而最後的 4.11-RELEASE 則在 2005 年 1 月發行。4-STABLE 分支的支援會持續到 2007/01/31 ,但主要焦點在於安全方面的漏洞、臭蟲及其他嚴重問題的修補。

期待已久的 5.0-RELEASE 在 2003/01/19 正式發行。這是將近開發三年的巔峰之作,同時 也開始加強多顆CPU(SMPng)的支援、kernel thread(KSE) 的支援、檔案系統採用 UFS2 以及支援 snapshot 等, 並支援 UltraSPARC® 和 ia64 平台、支援藍芽、32 bit 的 PCMCIA 等。之後於 2003 年 6 月發行了 5.1。 而 -CURRENT 這個發展主軸分支的最後 5.X 版本是在 2004 年 2 月正式發行的 5.2.1-RELEASE,在 5.X 系列進入 -STABLE (RELENG_5分支)之後,-CURRENT 就轉移為 6.X 系列。

RELENG_5 分支於 2004 年 8 月正式開跑,之後是 5.3-RELEASE ,它是 5-STABLE 分支的第一個發行版本。 最後的 5.5-RELEASE 是在 2006 年 5 月發行的,在此之後 RELENG_5 分支不再繼續。

RELENG_6 分支於 2005 年 7 月開跑,而 6.X 分支的第一個 release(6.0-RELEASE) 是在 2005 年 11 月出的。 最新的 9.3-RELEASE 是在 2006 年 5 月 發行。 當然囉,RELENG_6 分支還將有後續的發行版。

RELENG_7 分支於 2007 年 10 月開跑,最新的 10.2-RELEASE 是在 2006 年 5 月 發行。 RELENG_7 分支還將有後續的發行版。

目前,長期的開發計畫繼續在 8.X-CURRENT (trunk) 分支中進行,而 8.X 的 CD-ROM (當然,也可以用網路抓) snapshot 版本可以在 FreeBSD snapshot server 取得。

1.3.2. FreeBSD 計劃的目標

Contributed by Jordan Hubbard.

FreeBSD 計劃的目標在於提供可作任意用途的軟體而不附帶任何限制條文。 我們之中許多人對程式碼 (以及計畫本身) 都有非常大的投入, 因此,當然不介意偶爾有一些資金上的補償,但我們並沒打算堅決地要求得到這類資助。 我們認為我們的首要『使命(mission)』是為任何人提供程式碼, 不管他們打算用這些程式碼做什麼, 因為這樣程式碼將能夠被更廣泛地使用,從而發揮其價值。 我認為這是自由軟體最基本的,同時也是我們所倡導的一個目標。

我們程式碼樹中,有若干是以 GNU GPL 或者 LGPL 發佈的那些程式碼帶有少許的附加限制,還好只是強制性的要求開放程式碼而不是別的。 由於使用 GPL 的軟體在商業用途上會增加若干複雜性,因此,如果可以選擇的話, 我們會比較喜歡使用限制相對更寬鬆的 BSD 版權來發佈軟體。

1.3.3. FreeBSD 的開發模式

Contributed by Satoshi Asami.

FreeBSD 的開發是一個非常開放且具彈性的過程,就像從 貢獻者名單 所看到的,是由全世界成千上萬的貢獻者發展起來的。 FreeBSD 的開發基礎架構允許數以百計的開發者透過網際網路協同工作。 我們也經常關注著那些對我們的計畫感興趣的新開發者和新的創意, 那些有興趣更進一步參與計劃的人只需要在 FreeBSD technical discussions 郵遞論壇 連繫我們。 FreeBSD announcements 郵遞論壇 對那些希望了解我們進度的人也是相當有用的。

無論是單獨開發者或者封閉式的團隊合作,多瞭解 FreeBSD 計劃和它的開發過程會是不錯的︰

The SVN and CVS repository

過去數年來 FreeBSD 的中央 source tree 一直是以 CVS (Concurrent Versions System) 來維護的, 它是個自由軟體,可用來做為版本控制,一裝完 FreeBSD 內就有附了。 然而在 2008 年 6 月起, FreeBSD 版本控制系統改用 SVN(Subversion)。 這切換動作我們認為是有必要,因為 CVS 先天的技術限制,導致 source tree 以及歷史版本數量不斷快速擴張。 因此,主要的 repository 目前是採用 SVN ,而 client 端的工具像是 CVSupcsup 都是以舊式的 CVS 架構為基礎,仍可以繼續正常運作 —— 此乃因 SVN repository 有 backport 回 CVS 才可以繼續讓 client 端相容。 目前,就只有中央 source tree 是採 SVN 版本控制方式。 而文件、網頁、 Ports 這些 repository 仍持續使用 CVS 版本控制方式。 而主要的 CVS repository 是位於美國加州 Santa Clara 的某台機器上, 然後再 mirror 到世界上其他的許多機器上。 SVN tree 內有兩個主分支: -CURRENT 以及 -STABLE ,這些都可輕鬆複製到自己機器上。 詳情請參閱 更新你的 source tree 一節。

The committers list

所謂的 committers 指的是對 CVS tree 有 write 權限, 並依不同授權部分,而有不同權限可修改 FreeBSD source。 (committer 這詞源自 cvs(1) 中的 commit 指令,該指令是用來把新的修改提交給 CVS repository。) 而提交修改給 committer 們檢查的最好方式,就是用 send-pr(1) 指令。 若提交 PR 的流程系統上有壅塞現象的話, 也可以改用寄信方式,寄信到 FreeBSD committer's 郵遞論壇 即可。

The FreeBSD core team

如果把 FreeBSD 看成是一家公司的話, FreeBSD core team 就相當於『董事會(board of directors)』。 core team 的主要職責在於確保此計劃有良好的架構,以朝著正確的方向發展。 此外,邀請熱血且負責的軟體開發者加入 committers 行列, 以在若干成員離去時得以補充新血。 目前的 core team 是在 2008 年 7 月 committers 候選人中選出來的,每兩年會舉辦一次選舉。

有些 core team 成員還負責某些特定範圍, 也就是說他們必須盡量確保一些子系統的穩定、效能。 關於 FreeBSD 開發者們以及各自責任範圍,請參閱 貢獻者名單

注意:

core team 大部分成員加入 FreeBSD 開發都是志工性質而已, 並未從本計劃中獲得任何薪酬,所以不該把 commitment 誤解為 guaranteed support 才對。 剛前面所講的『董事會』可能是不恰當的類推,或許我們應該說: 他們是一群自願放棄原本的優渥生活、個人其他領域成就, 而選擇投入 FreeBSD 開發的熱血有為者才對!

其他的貢獻者

最後一點,但這點絕非最不重要的, 最大的開發者團隊就是持續為我們提供回饋以及錯誤修正的使用者自己。 與 FreeBSD 非核心開發者互動的主要方式,便是透過訂閱 FreeBSD technical discussions 郵遞論壇 來進行溝通,這方面可參考,請參閱 附錄 C, 網際網路上的資源 以瞭解各式不同的 FreeBSD 郵遞論壇(mailing lists)。

FreeBSD 貢獻者名單 相當長且不斷成長中, 只要有貢獻就會被列入其中, 要不要立即考慮貢獻 FreeBSD 一些回饋呢?

然而,提供原始碼並非為這個計劃做貢獻的唯一方式; 還需要大家投入的完整工作列表、說明,請參閱 FreeBSD 官網

簡單的說,我們的開發模式就像是一組沒有拘束的同心圓。 這種集中開發模式是以 給使用者方便 為主, 同時讓他們能很容易地共同維護軟體,而不會把潛在的貢獻者排除在外! 我們的目標是提供含有大量一致性的 應用軟體(ports/packages) ,以便讓使用者輕鬆安裝、使用的作業系統 —— 而這開發模式相當符合此一目標。

我們對於那些想要加入 FreeBSD 開發者的期待是: 請保持如同前人一樣的投入,以確保繼續成功!

1.3.4. 最新的 FreeBSD 發行版本

FreeBSD 是免費使用且帶有完整原始程式碼的以 4.4BSD-Lite 為基礎的系統,可以在 Intel i386™, i486™, Pentium®, Pentium® Pro, Celeron®, Pentium® II, Pentium® III, Pentium® 4 (或者相容型號), Xeon™, DEC Alpha™ 和 Sun UltraSPARC® 為基礎的電腦上執行的作業系統。 它主要以加州大學巴爾克利分校 的 CSRG 研究小組的軟體為基礎,並加入了 NetBSD、OpenBSD、386BSD 以及自由軟體基金會的一些東西。

自從 1994 年末,我們發佈了 FreeBSD 2.0 之後,系統的執行效率、 功能、穩定性都有了令人注目的提升。 最大的改變就是我們將記憶體與檔案系統的 cache 機制結合在一起。 這不只使得系統的表現變得更好, 並且使得 FreeBSD 系統最少的記憶體需求減少到 5 MB。 其它的改進包括完整的 NIS cilent and server 功能支援, 支援 transaction TCP、PPP 撥接連線、整合的 DHCP 支援、 SCSI 子系統的改進、ISDN 的支援,ATM、FDDI 以及乙太網路 (Ethernet、包括 100 Mbit 和 Gigabit) 的支援,提升了最新的 Adaptec 控制卡驅動程式的改善,以及數以千計的 bug 修正。

除了最基本的系統軟體,FreeBSD 還提供了廣受歡迎的套件軟體管理機制: Ports Collection。 到本書付印時,已有超過 24,000 個 ports,這範疇涵蓋從 http(WWW) 伺服器到遊戲、程式語言、編輯器以及您能想到的幾乎所有的東西。 完整的 Ports Collection 需要約 500 MB 的硬碟空間,除了 port 基本架構檔案外,都只儲存與該 port 軟體的原始碼有『須要變更』的部份。 如此一來,我們可以更容易更新這些 ports,也大量的減少如舊的 1.0 版 Ports Collection 對於硬碟空間的需求。 要安裝一個 port 的話,只需要進入該 port 的目錄,輸入 make install,這樣子系統就會幫你裝好了。 您要編譯的每個程式的完整原始程式, 都可從 FTP 或 CD-ROM 中獲得,所以您只需準備足夠的硬碟空間來編譯你要的 port 軟體。 幾乎每一個 port 都有已事先編譯好的 package以方便安裝, 如果不想從編譯 port 的人,只要用個簡單指令 (pkg_add)就可以安裝。 有關 packages 和 ports 的細節,可以參閱 章 4, 軟體套件管理篇:Packages 及 Ports 機制

FreeBSD 主機的 /usr/share/doc 目錄下找到許多有用的文件, 來幫助您安裝、使用 FreeBSD。 也可以使用下面的網址,以瀏覽器來翻閱本機上安裝的手冊︰

FreeBSD 使用手冊

/usr/share/doc/handbook/index.html

FreeBSD 常見問答集

/usr/share/doc/faq/index.html

此外,可在下列網址找到最新版 (也是更新最頻繁的版本):http://www.FreeBSD.org/

章 2. 安裝 FreeBSD 9.X 和更新的版本

Restructured, reorganized, and parts rewritten by Jim Mock.
Updated for bsdinstall by Gavin AtkinsonWarren Block.
Updated for root-on-ZFS by Allan Jude.

2.1. 概述

自從 FreeBSD 9.0-RELEASE開始, FreeBSD 提供一個易用,文字介面的安裝程式 bsdinstall。 本章描述如何用 bsdinstall來安裝 FreeBSD。

一般來說,本章所寫的安裝說明是針對i386™ 和 AMD64 架構。如果可以用於其他平台,將會列表說明。 安裝程式和本章所敘述的內容可能會有些微差異,所以請將本章視為通用的指引,而不是完全照著來做。

注意:

喜歡用圖形化安裝程式安裝 FreeBSD 的使用者, 可能會對 pc-sysinstall有興趣,這是PC-BSD計畫所使用的。 他可以用來安裝圖形化桌面 (PC-BSD) 或是命令列版本的 FreeBSD。 細節請參考 PC-BSD 使用者 Handbook (http://wiki.pcbsd.org/index.php/PC-BSD%C2%AE_Users_Handbook/10.1)。

讀完這章,您將了解:

  • 最低的硬體需求和 FreeBSD 支援的架構。

  • 如何建立 FreeBSD 的安裝媒體。

  • 如何開始執行 bsdinstall

  • bsdinstall會詢問的問題,問題代表的意思,以及如何回答。

  • 安裝失敗時如何做故障排除。

  • 如何在正式安裝前使用 live 版本的 FreeBSD。

在開始閱讀這章之前,您需要︰

  • 閱讀即將安裝的 FreeBSD 版本所附帶的硬體支援清單,並核對系統的硬體是否有支援。

2.2. 最低硬體需求

安裝 FreeBSD 的硬體需求隨 FreeBSD 的版本和硬體架構而不同。 FreeBSD發行版支援的硬體架構和裝置列在硬體支援清單的檔案裡。 這個檔案通常名為 HARDWARE.TXT,位於發行媒體的根目錄。 支援硬體清單的副本也可以在FreeBSD 網站 (http://www.FreeBSD.org/releases/index.html)的發行資訊頁面找到。

FreeBSD 最小安裝需要至少 64 MB 的 RAM 和 1.5 GB 的可用硬碟空間 但是這真的是 最小,幾乎沒有剩下多餘的空間。 較實際的安裝,不用圖形化環境最少需要 4 GB ,如果要用圖形化介面至少要有 8 GB 以上。 第三方應用程式需要更多空間。建議增加 It is recommended to increase RAM 和硬碟空間以應付應用程式的需求和未來可能儲存的資料量。

每一種架構的處理器需求概述如下:

amd64

有兩類處理器可以跑 amd64。 第一類是 AMD64 處理器,包括 AMD Athlon™64 和 AMD Opteron™ 處理器。

第二類包括那些使用 Intel® EM64T 架構的處理器。 這些包括除了Sossaman以外的所有多核心 Intel® Xeon™ 處理器。 單核心 Intel® Xeon™ 處理器 Nocona, Irwindale, Potomac, 和 Cranford, Intel® Core™ 2 (非 Core Duo) 和更新的處理器,所有的 Intel® Pentium® D 處理器, 和某些 Intel® Pentium® 4s 與使用Prescott核心的 Celeron Ds 。

單處理器 (UP) 和對稱多處理器 (SMP)的設定都有支援。

i386

幾乎所有有浮點運算裝置的 i386 相容處理器都有支援。所有 Intel® 486或是更新的處理器也有支援。

如果 CPUs 有支援,FreeBSD 會利用實體位址延伸 有開啟 PAE 支援的核心會偵測超過 4 GB 的記憶體,讓他能被系統使用。 這項功能為 FreeBSD 的驅動程式與部分功能帶來一些限制,詳情請見 pae(4)

ia64

目前支援的處理器是 Itanium® 和 Itanium® 2。支援的晶片組包括 HP zx1, Intel® 460GX 和 Intel® E8870。 單處理器 (UP) 和對稱多處理器 (SMP)的設定都有支援。

pc98

NEC PC-9801/9821 系列幾乎所有 i386 相容處理器包括 80486, Pentium®, Pentium® Pro 和 Pentium® II 都有支援。 所有 AMD, Cyrix, IBM, and IDT 的i386 相容處理器都有支援。 相容NEC PC-9801 的EPSON PC-386/486/586 系列都有支援。 NEC FC-9801/9821 and NEC SV-98 系列也有支援。

高解析度模式並不支援。NEC PC-98XA/XL/RL/XL^2 和 NEC PC-H98 系列只支援正常 (PC-9801 相容) 模式。 FreeBSD 對稱多處理器 SMP 相關特色並不支援。 PC-H98, SV-H98 和FC-H98 新延伸標準架構 (NESA) 匯流排不支援。

powerpc

所有內建USB的 New World ROM Apple® Mac® 系統都有支援。 SMP 在多 CPUs的機器都有支援。

32位元的核心只能使用前 2 GB的RAM

sparc64

FreeBSD/sparc64 支援的系統列在 FreeBSD/sparc64 計劃 (http://www.freebsd.org/platforms/sparc.html).

所有超過一個處理器的系統都有支援SMP。需要專用的磁碟系統,因為此時無法和其他作業系統共用磁碟。

2.3. 安裝前的工作

一旦確定系統符合安裝 FreeBSD 的最低硬體需求,就可以下載安裝檔案並準備安裝的媒體。 做這些之前,先檢查以下核對清單的項目是否準備好了:

  1. 備份重要資料

    安裝任何作業系統前, 總是 要先備份所有重要資料。 不要儲存備份在即將安裝的系統上。改為將資料儲存在可移除磁碟,像是 USB 隨身碟,網路上的另一個系統或是線上備份服務上。 開始安裝前,要測試備份,確定它含有所有需要的檔案。 一旦安裝程式格式化系統的磁碟,所有儲存在上面的資料都會遺失。

  2. 決定 FreeBSD 安裝在哪裡

    如果 FreeBSD 是唯一要安裝的作業系統,這個步驟可以略過。 但是假如 FreeBSD 將和其他作業系統分享磁碟空間的話,要決定 FreeBSD 要安裝在哪個磁碟或是哪個分割區。

    在 i386 和 amd64 平台,磁碟可以使用兩種分割區配置之一來分割成多個分割區。 傳統的主開機紀錄 (MBR) 有一個分割區表定義最多到 主分割區。 因為歷史性的理由, FreeBSD稱這些主分割區為 slices。 其中一個主分割區可以分成一個 延伸分割區 ,他包含多個 邏輯分割區GUID 分割區表 (GPT) 是較新和較簡單的分割磁碟的方法 一般GPT 實作允許每個磁碟最多達128個分割區,減少使用邏輯分割區的需要。

    警告:

    一些比較舊的作業系統,像是 Windows® XP , 和 GPT 分割區配置並不相容。 如果 FreeBSD 將和這樣的作業系統共享一個磁碟,那就需要用 MBR 分割。

    FreeBSD 開機啟動程式需要主分割區或是 GPT 分割區。 如果所有的主分割區或 GPT 分割區都已使用, 必須釋放其中一個分割區讓 FreeBSD 使用。 如果要建立一個分割區而不刪除原有的資料, 可以使用磁碟分割工具來縮小現有的分割區, 並使用多出的空間來建立新分割區。

    各種自由的和商業化的磁碟分割工具列於 http://en.wikipedia.org/wiki/List_of_disk_partitioning_softwareGParted Live (http://gparted.sourceforge.net/livecd.php) 是包含分割編輯工具GParted的自由的 live CDGParted 也包含在許多 Linux live CD 套件裡。

    警告:

    當正確地使用,磁碟分割工具可以安全地建立空間讓新的分割區使用。 因為有可能會誤選已經存在的分割區,所以在修改磁碟分割區前, 一定要備份重要資料,並確認備份的完整性。

    包含不同作業系統的磁碟分割區可以讓一台電腦安裝多重作業系統。 另一種作法是使用虛擬機器 (章 21, Virtualization(虛擬機器)) ,可以讓多重作業系統同時間執行而不需要改變任何磁碟分割區。

  3. 收集網路資訊

    有些 FreeBSD 安裝方法為了下載安裝檔案需要網路連線。 在系統安裝之後,安裝程式將會讓您設定系統的網路介面。

    如果網路有 DHCP 伺服器,可以自動設定網路。 如果沒有 DHCP , 需要從區域網路管理者或是網際網路服務商取得以下系統的網路資訊:

    需要的網路資訊
    1. IP 位址

    2. 子網路遮罩

    3. 預設閘道器 IP 位址

    4. 網路的網域名稱

    5. 網路 DNS 伺服器 IP 位址

  4. 檢查 FreeBSD 勘誤表

    儘管 FreeBSD Project 努力確保每個 FreeBSD 發行版能夠儘可能地穩定,錯誤偶爾還是會悄悄出現。 有極小的機會錯誤會影響安裝過程。 當這些問題被發現並修正後,會被紀錄在 FreeBSD 網站的 FreeBSD 勘誤表 (http://www.freebsd.org/releases/10.2R/errata.html)。 安裝前要檢查勘誤表,確保沒有會影響到安裝的問題。

    所有發行版的資訊和勘誤表可以在 FreeBSD 網站的發行資訊找到 (http://www.freebsd.org/releases/index.html)。

2.3.1. 準備安裝的媒體

The FreeBSD installer is not an application that can be run from within another operating system. Instead, download a FreeBSD installation file, burn it to the media associated with its file type and size (CD, DVD, or USB), and boot the system to install from the inserted media.

FreeBSD installation files are available at www.freebsd.org/where.html#download. Each installation file's name includes the release version of FreeBSD, the architecture, and the type of file. For example, to install FreeBSD 10.0 on an amd64 system from a DVD, download FreeBSD-10.0-RELEASE-amd64-dvd1.iso, burn this file to a DVD, and boot the system with the DVD inserted.

Several file types are available, though not all file types are available for all architectures. The possible file types are:

  • -bootonly.iso: This is the smallest installation file as it only contains the installer. A working Internet connection is required during installation as the installer will download the files it needs to complete the FreeBSD installation. This file should be burned to a CD using a CD burning application.

  • -disc1.iso: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. It should be burned to a CD using a CD burning application.

  • -dvd1.iso: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. It also contains a set of popular binary packages for installing a window manager and some applications so that a complete system can be installed from media without requiring a connection to the Internet. This file should be burned to a DVD using a DVD burning application.

  • -memstick.img: This file contains all of the files needed to install FreeBSD, its source, and the Ports Collection. It should be burned to a USB stick using the instructions below.

Also download CHECKSUM.SHA256 from the same directory as the image file and use it to check the image file's integrity by calculating a checksum. FreeBSD provides sha256(1) for this, while other operating systems have similar programs. Compare the calculated checksum with the one shown in CHECKSUM.SHA256. The checksums must match exactly. If the checksums do not match, the file is corrupt and should be downloaded again.

2.3.1.1. 將印象檔寫入USB

The *.img file is an image of the complete contents of a memory stick. It cannot be copied to the target device as a file. Several applications are available for writing the *.img to a USB stick. This section describes two of these utilities.

重要:

Before proceeding, back up any important data on the USB stick. This procedure will erase the existing data on the stick.

過程 2.1. 使用 dd 指令來寫入印象檔

警告:

This example uses /dev/da0 as the target device where the image will be written. Be very careful that the correct device is used as this command will destroy the existing data on the specified target device.

  • The dd(1) command-line utility is available on BSD, Linux®, and Mac OS® systems. To burn the image using dd, insert the USB stick and determine its device name. Then, specify the name of the downloaded installation file and the device name for the USB stick. This example burns the amd64 installation image to the first USB device on an existing FreeBSD system.

    # dd if=FreeBSD-10.0-RELEASE-amd64-memstick.img of=/dev/da0 bs=64k

    If this command fails, verify that the USB stick is not mounted and that the device name is for the disk, not a partition. Some operating systems might require this command to be run with sudo(8). Systems like Linux® might buffer writes. To force all writes to complete, use sync(8).

過程 2.2. 使用Windows® 來寫入映象檔

警告:

要確保提供正確的磁碟機代號,因為磁碟上的資料會被覆蓋和摧毀。

  1. 取得Image Writer for Windows®

    Image Writer for Windows® 是一個免費的應用程式,可以正確地將映像檔寫入隨身碟。 從 https://launchpad.net/win32-image-writer/ 下載,並解壓縮到一個資料夾。

  2. 用 Image Writer 寫入映象檔

    雙擊 Win32DiskImager icon 啟動程式。 確認 Device 顯示的磁碟機代號是隨身碟的磁碟機代號。 按下資料夾 icon 選擇要寫入隨身碟的映像檔。 按下 [ Save ] 按鈕確定映像檔名。 確認所有東西都正確,隨身碟的資料夾並沒有在其他視窗開啟。 所有東西準備好後,按下 [ Write ] 將映像檔寫入隨身碟。

您現在可以開始安裝 FreeBSD 。

2.4. 開始安裝

重要:

By default, the installation will not make any changes to the disk(s) before the following message:

Your changes will now be written to disk.  If you
have chosen to overwrite existing data, it will
be PERMANENTLY ERASED. Are you sure you want to
commit your changes?

The install can be exited at any time prior to this warning. If there is a concern that something is incorrectly configured, just turn the computer off before this point and no changes will be made to the system's disks.

This section describes how to boot the system from the installation media which was prepared using the instructions in 節 2.3.1, “準備安裝的媒體”. When using a bootable USB stick, plug in the USB stick before turning on the computer. When booting from CD or DVD, turn on the computer and insert the media at the first opportunity. How to configure the system to boot from the inserted media depends upon the architecture.

2.4.1. Booting on i386™ and amd64

These architectures provide a BIOS menu for selecting the boot device. Depending upon the installation media being used, select the CD/DVD or USB device as the first boot device. Most systems also provide a key for selecting the boot device during startup without having to enter the BIOS. Typically, the key is either F10, F11, F12, or Escape.

If the computer loads the existing operating system instead of the FreeBSD installer, then either:

  1. The installation media was not inserted early enough in the boot process. Leave the media inserted and try restarting the computer.

  2. The BIOS changes were incorrect or not saved. Double-check that the right boot device is selected as the first boot device.

  3. This system is too old to support booting from the chosen media. In this case, the Plop Boot Manager (http://www.plop.at/en/bootmanager.html) can be used to boot the system from the selected media.

2.4.2. Booting on PowerPC®

On most machines, holding C on the keyboard during boot will boot from the CD. Otherwise, hold Command+Option+O+F, or Windows+Alt+O+F on non-Apple® keyboards. At the 0 > prompt, enter

boot cd:,\ppc\loader cd:0

2.4.3. Booting on Sparc64®

Most Sparc64® systems are set up to boot automatically from disk. To install FreeBSD from a CD requires a break into the PROM.

To do this, reboot the system and wait until the boot message appears. The message depends on the model, but should look something like this:

Sun Blade 100 (UltraSPARC-IIe), Keyboard Present
Copyright 1998-2001 Sun Microsystems, Inc.  All rights reserved.
OpenBoot 4.2, 128 MB memory installed, Serial #51090132.
Ethernet address 0:3:ba:b:92:d4, Host ID: 830b92d4.

If the system proceeds to boot from disk at this point, press L1+A or Stop+A on the keyboard, or send a BREAK over the serial console. When using tip or cu, ~# will issue a BREAK. The PROM prompt will be ok on systems with one CPU and ok {0} on SMP systems, where the digit indicates the number of the active CPU.

At this point, place the CD into the drive and type boot cdrom from the PROM prompt.

2.4.4. FreeBSD 開機選單

Once the system boots from the installation media, a menu similar to the following will be displayed:

圖形 2.1. FreeBSD 開機管理程式選單
FreeBSD 開機管理程式選單

By default, the menu will wait ten seconds for user input before booting into the FreeBSD installer or, if FreeBSD is already installed, before booting into FreeBSD. To pause the boot timer in order to review the selections, press Space. To select an option, press its highlighted number, character, or key. The following options are available.

  • Boot Multi User: This will continue the FreeBSD boot process. If the boot timer has been paused, press 1, upper- or lower-case B, or Enter.

  • Boot Single User: This mode can be used to fix an existing FreeBSD installation as described in 節 12.6.2, “Single-User Mode”. Press 2 or the upper- or lower-case S to enter this mode.

  • Escape to loader prompt: This will boot the system into a repair prompt that contains a limited number of low-level commands. This prompt is described in 節 12.3.3, “Stage Three, /boot/loader. Press 3 or Esc to boot into this prompt.

  • Reboot: Reboots the system.

  • Configure Boot Options: Opens the menu shown in, and described under, 圖形 2.2, “FreeBSD 開機選項選單”.

圖形 2.2. FreeBSD 開機選項選單
FreeBSD 開機選項選單

The boot options menu is divided into two sections. The first section can be used to either return to the main boot menu or to reset any toggled options back to their defaults.

The next section is used to toggle the available options to On or Off by pressing the option's highlighted number or character. The system will always boot using the settings for these options until they are modified. Several options can be toggled using this menu:

  • ACPI Support: If the system hangs during boot, try toggling this option to Off.

  • Safe Mode: If the system still hangs during boot even with ACPI Support set to Off, try setting this option to On.

  • Single User: Toggle this option to On to fix an existing FreeBSD installation as described in 節 12.6.2, “Single-User Mode”. Once the problem is fixed, set it back to Off.

  • Verbose: Toggle this option to On to see more detailed messages during the boot process. This can be useful when troubleshooting a piece of hardware.

After making the needed selections, press 1 or Backspace to return to the main boot menu, then press Enter to continue booting into FreeBSD. A series of boot messages will appear as FreeBSD carries out its hardware device probes and loads the installation program. Once the boot is complete, the welcome menu shown in 圖形 2.3, “歡迎選單” will be displayed.

圖形 2.3. 歡迎選單
歡迎選單

Press Enter to select the default of [ Install ] to enter the installer. The rest of this chapter describes how to use this installer. Otherwise, use the right or left arrows or the colorized letter to select the desired menu item. The [ Shell ] can be used to access a FreeBSD shell in order to use command line utilities to prepare the disks before installation. The [ Live CD ] option can be used to try out FreeBSD before installing it. The live version is described in 節 2.10, “使用 Live CD.

提示:

To review the boot messages, including the hardware device probe, press the upper- or lower-case S and then Enter to access a shell. At the shell prompt, type more /var/run/dmesg.boot and use the space bar to scroll through the messages. When finished, type exit to return to the welcome menu.

2.5. 使用 bsdinstall

This section shows the order of the bsdinstall menus and the type of information that will be asked before the system is installed. Use the arrow keys to highlight a menu option, then Space to select or deselect that menu item. When finished, press Enter to save the selection and move onto the next screen.

2.5.1. Selecting the Keymap Menu

Depending on the system console being used, bsdinstall may initially display the menu shown in 圖形 2.4, “Keymap Selection”.

圖形 2.4. Keymap Selection
Keymap Selection

To configure the keyboard layout, press Enter with [ YES ] selected, which will display the menu shown in 圖形 2.5, “選擇鍵盤選單”. To instead use the default layout, use the arrow key to select [ NO ] and press Enter to skip this menu screen.

圖形 2.5. 選擇鍵盤選單
選擇鍵盤選單

When configuring the keyboard layout, use the up and down arrows to select the keymap that most closely represents the mapping of the keyboard attached to the system. Press Enter to save the selection.

注意:

Pressing Esc will exit this menu and use the default keymap. If the choice of keymap is not clear, United States of America ISO-8859-1 is also a safe option.

In FreeBSD 10.0-RELEASE and later, this menu has been enhanced. The full selection of keymaps is shown, with the default preselected. In addition, when selecting a different keymap, a dialog is displayed that allows the user to try the keymap and ensure it is correct before proceeding.

圖形 2.6. Enhanced Keymap Menu
Enhanced Keymap Menu

2.5.2. 設定主機名稱

The next bsdinstall menu is used to set the hostname for the newly installed system.

圖形 2.7. 設定主機名稱
設定主機名稱

Type in a hostname that is unique for the network. It should be a fully-qualified hostname, such as machine3.example.com.

2.5.3. 選擇要安裝的組件

Next, bsdinstall will prompt to select optional components to install.

圖形 2.8. 選擇要安裝的組件
選擇要安裝的組件

Deciding which components to install will depend largely on the intended use of the system and the amount of disk space available. The FreeBSD kernel and userland, collectively known as the base system, are always installed. Depending on the architecture, some of these components may not appear:

  • doc - Additional documentation, mostly of historical interest, to install into /usr/share/doc. The documentation provided by the FreeBSD Documentation Project may be installed later using the instructions in 節 23.3, “更新文件組”.

  • games - Several traditional BSD games, including fortune, rot13, and others.

  • lib32 - Compatibility libraries for running 32-bit applications on a 64-bit version of FreeBSD.

  • ports - The FreeBSD Ports Collection is a collection of files which automates the downloading, compiling and installation of third-party software packages. 章 4, 軟體套件管理篇:Packages 及 Ports 機制 discusses how to use the Ports Collection.

    警告:

    The installation program does not check for adequate disk space. Select this option only if sufficient hard disk space is available. The FreeBSD Ports Collection takes up about 500 MB of disk space.

  • src - The complete FreeBSD source code for both the kernel and the userland. Although not required for the majority of applications, it may be required to build device drivers, kernel modules, or some applications from the Ports Collection. It is also used for developing FreeBSD itself. The full source tree requires 1 GB of disk space and recompiling the entire FreeBSD system requires an additional 5 GB of space.

2.5.4. 從網路安裝

The menu shown in 圖形 2.9, “從網路安裝” only appears when installing from a -bootonly.iso CD as this installation media does not hold copies of the installation files. Since the installation files must be retrieved over a network connection, this menu indicates that the network interface must be first configured.

圖形 2.9. 從網路安裝
從網路安裝

To configure the network connection, press Enter and follow the instructions in 節 2.8.2, “Configuring Network Interfaces”. Once the interface is configured, select a mirror site that is located in the same region of the world as the computer on which FreeBSD is being installed. Files can be retrieved more quickly when the mirror is close to the target computer, reducing installation time.

圖形 2.10. 選擇鏡像站
選擇鏡像站

Installation will then continue as if the installation files were located on the local installation media.

2.6. 配置磁碟空間

The next menu is used to determine the method for allocating disk space. The options available in the menu depend upon the version of FreeBSD being installed.

圖形 2.11. Partitioning Choices on FreeBSD 9.x
Partitioning Choices on FreeBSD 9.x

圖形 2.12. Partitioning Choices on FreeBSD 10.x and Higher
Partitioning Choices on FreeBSD 10.x and Higher

Guided partitioning automatically sets up the disk partitions, Manual partitioning allows advanced users to create customized partitions from menu options, and Shell opens a shell prompt where advanced users can create customized partitions using command-line utilities like gpart(8), fdisk(8), and bsdlabel(8). ZFS partitioning, only available in FreeBSD 10 and later, creates an optionally encrypted root-on-ZFS system with support for boot environments.

This section describes what to consider when laying out the disk partitions. It then demonstrates how to use the different partitioning methods.

2.6.1. Designing the Partition Layout

When laying out file systems, remember that hard drives transfer data faster from the outer tracks to the inner. Thus, smaller and heavier-accessed file systems should be closer to the outside of the drive, while larger partitions like /usr should be placed toward the inner parts of the disk. It is a good idea to create partitions in an order similar to: /, swap, /var, and /usr.

The size of the /var partition reflects the intended machine's usage. This partition is used to hold mailboxes, log files, and printer spools. Mailboxes and log files can grow to unexpected sizes depending on the number of users and how long log files are kept. On average, most users rarely need more than about a gigabyte of free disk space in /var.

注意:

Sometimes, a lot of disk space is required in /var/tmp. When new software is installed, the packaging tools extract a temporary copy of the packages under /var/tmp. Large software packages, like Firefox, OpenOffice or LibreOffice may be tricky to install if there is not enough disk space under /var/tmp.

The /usr partition holds many of the files which support the system, including the FreeBSD Ports Collection and system source code. At least 2 gigabytes is recommended for this partition.

When selecting partition sizes, keep the space requirements in mind. Running out of space in one partition while barely using another can be a hassle.

As a rule of thumb, the swap partition should be about double the size of physical memory (RAM). Systems with minimal RAM may perform better with more swap. Configuring too little swap can lead to inefficiencies in the VM page scanning code and might create issues later if more memory is added.

On larger systems with multiple SCSI disks or multiple IDE disks operating on different controllers, it is recommended that swap be configured on each drive, up to four drives. The swap partitions should be approximately the same size. The kernel can handle arbitrary sizes but internal data structures scale to 4 times the largest swap partition. Keeping the swap partitions near the same size will allow the kernel to optimally stripe swap space across disks. Large swap sizes are fine, even if swap is not used much. It might be easier to recover from a runaway program before being forced to reboot.

By properly partitioning a system, fragmentation introduced in the smaller write heavy partitions will not bleed over into the mostly read partitions. Keeping the write loaded partitions closer to the disk's edge will increase I/O performance in the partitions where it occurs the most. While I/O performance in the larger partitions may be needed, shifting them more toward the edge of the disk will not lead to a significant performance improvement over moving /var to the edge.

2.6.2. Guided Partitioning

When this method is selected, a menu will display the available disk(s). If multiple disks are connected, choose the one where FreeBSD is to be installed.

圖形 2.13. Selecting from Multiple Disks
Selecting from Multiple Disks

Once the disk is selected, the next menu prompts to install to either the entire disk or to create a partition using free space. If [ Entire Disk ] is chosen, a general partition layout filling the whole disk is automatically created. Selecting [ Partition ] creates a partition layout from the unused space on the disk.

圖形 2.14. Selecting Entire Disk or Partition
Selecting Entire Disk or Partition

After the partition layout has been created, review it to ensure it meets the needs of the installation. Selecting [ Revert ] will reset the partitions to their original values and pressing [ Auto ] will recreate the automatic FreeBSD partitions. Partitions can also be manually created, modified, or deleted. When the partitioning is correct, select [ Finish ] to continue with the installation.

圖形 2.15. Review Created Partitions
Review Created Partitions

2.6.3. Manual Partitioning

Selecting this method opens the partition editor:

圖形 2.16. Manually Create Partitions
Manually Create Partitions

Highlight the installation drive (ada0 in this example) and select [ Create ] to display a menu of available partition schemes:

圖形 2.17. Manually Create Partitions
Manually Create Partitions

GPT is usually the most appropriate choice for amd64 computers. Older computers that are not compatible with GPT should use MBR. The other partition schemes are generally used for uncommon or older computers.

表格 2.1. Partitioning Schemes
AbbreviationDescription
APMApple Partition Map, used by PowerPC®.
BSDBSD label without an MBR, sometimes called dangerously dedicated mode as non-BSD disk utilities may not recognize it.
GPTGUID Partition Table (http://en.wikipedia.org/wiki/GUID_Partition_Table).
MBRMaster Boot Record (http://en.wikipedia.org/wiki/Master_boot_record).
PC98MBR variant used by NEC PC-98 computers (http://en.wikipedia.org/wiki/Pc9801).
VTOC8Volume Table Of Contents used by Sun SPARC64 and UltraSPARC computers.

After the partitioning scheme has been selected and created, select [ Create ] again to create the partitions.

圖形 2.18. Manually Create Partitions
Manually Create Partitions

A standard FreeBSD GPT installation uses at least three partitions:

  • freebsd-boot - Holds the FreeBSD boot code.

  • freebsd-ufs - A FreeBSD UFS file system.

  • freebsd-swap - FreeBSD swap space.

Another partition type worth noting is freebsd-zfs, used for partitions that will contain a FreeBSD ZFS file system (章 19, The Z File System (ZFS)). Refer to gpart(8) for descriptions of the available GPT partition types.

Multiple file system partitions can be created and some people prefer a traditional layout with separate partitions for /, /var, /tmp, and /usr. See 範例 2.1, “Creating Traditional Split File System Partitions” for an example.

The Size may be entered with common abbreviations: K for kilobytes, M for megabytes, or G for gigabytes.

提示:

Proper sector alignment provides the best performance, and making partition sizes even multiples of 4K-bytes helps to ensure alignment on drives with either 512-byte or 4K-byte sectors. Generally, using partition sizes that are even multiples of 1M or 1G is the easiest way to make sure every partition starts at an even multiple of 4K. There is one exception: the freebsd-boot partition should be no larger than 512K due to current boot code limitations.

A Mountpoint is needed if the partition will contain a file system. If only a single UFS partition will be created, the mountpoint should be /.

The Label is a name by which the partition will be known. Drive names or numbers can change if the drive is connected to a different controller or port, but the partition label does not change. Referring to labels instead of drive names and partition numbers in files like /etc/fstab makes the system more tolerant to hardware changes. GPT labels appear in /dev/gpt/ when a disk is attached. Other partitioning schemes have different label capabilities and their labels appear in different directories in /dev/.

提示:

Use a unique label on every partition to avoid conflicts from identical labels. A few letters from the computer's name, use, or location can be added to the label. For instance, use labroot or rootfslab for the UFS root partition on the computer named lab.

範例 2.1. Creating Traditional Split File System Partitions

For a traditional partition layout where the /, /var, /tmp, and /usr directories are separate file systems on their own partitions, create a GPT partitioning scheme, then create the partitions as shown. Partition sizes shown are typical for a 20G target disk. If more space is available on the target disk, larger swap or /var partitions may be useful. Labels shown here are prefixed with ex for example, but readers should use other unique label values as described above.

By default, FreeBSD's gptboot expects the first UFS partition to be the / partition.

Partition TypeSizeMountpointLabel
freebsd-boot512K  
freebsd-ufs2G/exrootfs
freebsd-swap4G exswap
freebsd-ufs2G/varexvarfs
freebsd-ufs1G/tmpextmpfs
freebsd-ufsaccept the default (remainder of the disk)/usrexusrfs

After the custom partitions have been created, select [ Finish ] to continue with the installation.

2.6.4. Root-on-ZFS Automatic Partitioning

Support for automatic creation of root-on-ZFS installations was added in FreeBSD 10.0-RELEASE. This partitioning mode only works with whole disks and will erase the contents of the entire disk. The installer will automatically create partitions aligned to 4k boundaries and force ZFS to use 4k sectors. This is safe even with 512 byte sector disks, and has the added benefit of ensuring that pools created on 512 byte disks will be able to have 4k sector disks added in the future, either as additional storage space or as replacements for failed disks. The installer can also optionally employ GELI disk encryption as described in 節 17.13.2, “Disk Encryption with geli. If encryption is enabled, a 2 GB unencrypted boot pool containing the /boot directory is created. It holds the kernel and other files necessary to boot the system. A swap partition of a user selectable size is also created, and all remaining space is used for the ZFS pool.

The main ZFS configuration menu offers a number of options to control the creation of the pool.

圖形 2.19. ZFS Partitioning Menu
ZFS Partitioning Menu

Select T to configure the Pool Type and the disk(s) that will constitute the pool. The automatic ZFS installer currently only supports the creation of a single top level vdev, except in stripe mode. To create more complex pools, use the instructions in 節 2.6.5, “Shell Mode Partitioning” to create the pool. The installer supports the creation of various pool types, including stripe (not recommended, no redundancy), mirror (best performance, least usable space), and RAID-Z 1, 2, and 3 (with the capability to withstand the concurrent failure of 1, 2, and 3 disks, respectively). while selecting the pool type, a tooltip is displayed across the bottom of the screen with advice about the number of required disks, and in the case of RAID-Z, the optimal number of disks for each configuration.

圖形 2.20. ZFS Pool Type
ZFS Pool Type

Once a Pool Type has been selected, a list of available disks is displayed, and the user is prompted to select one or more disks to make up the pool. The configuration is then validated, to ensure enough disks are selected. If not, select <Change Selection> to return to the list of disks, or <Cancel> to change the pool type.

圖形 2.21. Disk Selection
Disk Selection

圖形 2.22. Invalid Selection
Invalid Selection

If one or more disks are missing from the list, or if disks were attached after the installer was started, select - Rescan Devices to repopulate the list of available disks. To ensure that the correct disks are selected, so as not to accidently destroy the wrong disks, the - Disk Info menu can be used to inspect each disk, including its partition table and various other information such as the device model number and serial number, if available.

圖形 2.23. Analysing a Disk
Analysing a Disk

The main ZFS configuration menu also allows the user to enter a pool name, disable forcing 4k sectors, enable or disable encryption, switch between GPT (recommended) and MBR partition table types, and select the amount of swap space. Once all options have been set to the desired values, select the >>> Install option at the top of the menu.

If GELI disk encryption was enabled, the installer will prompt twice for the passphrase to be used to encrypt the disks.

圖形 2.24. Disk Encryption Password
Disk Encryption Password

The installer then offers a last chance to cancel before the contents of the selected drives are destroyed to create the ZFS pool.

圖形 2.25. Last Chance
Last Chance

The installation then proceeds normally.

2.6.5. Shell Mode Partitioning

When creating advanced installations, the bsdinstall paritioning menus may not provide the level of flexibility required. Advanced users can select the Shell option from the partitioning menu in order to manually partition the drives, create the file system(s), populate /tmp/bsdinstall_etc/fstab, and mount the file systems under /mnt. Once this is done, type exit to return to bsdinstall and continue the installation.

2.7. Committing to the Installation

Once the disks are configured, the next menu provides the last chance to make changes before the selected hard drive(s) are formatted. If changes need to be made, select [ Back ] to return to the main partitioning menu. [ Revert & Exit ] will exit the installer without making any changes to the hard drive.

圖形 2.26. Final Confirmation
Final Confirmation

To instead start the actual installation, select [ Commit ] and press Enter.

Installation time will vary depending on the distributions chosen, installation media, and speed of the computer. A series of messages will indicate the progress.

First, the installer formats the selected disk(s) and initializes the partitions. Next, in the case of a bootonly media, it downloads the selected components:

圖形 2.27. Fetching Distribution Files
Fetching Distribution Files

Next, the integrity of the distribution files is verified to ensure they have not been corrupted during download or misread from the installation media:

圖形 2.28. Verifying Distribution Files
Verifying Distribution Files

Finally, the verified distribution files are extracted to the disk:

圖形 2.29. Extracting Distribution Files
Extracting Distribution Files

Once all requested distribution files have been extracted, bsdinstall displays the first post-installation configuration screen. The available post-configuration options are described in the next section.

2.8. Post-Installation

Once FreeBSD is installed, bsdinstall will prompt to configure several options before booting into the newly installed system. This section describes these configuration options.

提示:

Once the system has booted, bsdconfig provides a menu-driven method for configuring the system using these and additional options.

2.8.1. Setting the root Password

First, the root password must be set. While entering the password, the characters being typed are not displayed on the screen. After the password has been entered, it must be entered again. This helps prevent typing errors.

圖形 2.30. Setting the root Password
Setting the root Password

2.8.2. Configuring Network Interfaces

Next, a list of the network interfaces found on the computer is shown. Select the interface to configure.

注意:

The network configuration menus will be skipped if the network was previously configured as part of a bootonly installation.

圖形 2.31. Choose a Network Interface
Choose a Network Interface

If an Ethernet interface is selected, the installer will skip ahead to the menu shown in 圖形 2.35, “Choose IPv4 Networking”. If a wireless network interface is chosen, the system will instead scan for wireless access points:

圖形 2.32. Scanning for Wireless Access Points
Scanning for Wireless Access Points

Wireless networks are identified by a Service Set Identifier (SSID), a short, unique name given to each network. SSIDs found during the scan are listed, followed by a description of the encryption types available for that network. If the desired SSID does not appear in the list, select [ Rescan ] to scan again. If the desired network still does not appear, check for problems with antenna connections or try moving the computer closer to the access point. Rescan after each change is made.

圖形 2.33. Choosing a Wireless Network
Choosing a Wireless Network

Next, enter the encryption information for connecting to the selected wireless network. WPA2 encryption is strongly recommended as older encryption types, like WEP, offer little security. If the network uses WPA2, input the password, also known as the Pre-Shared Key (PSK). For security reasons, the characters typed into the input box are displayed as asterisks.

圖形 2.34. WPA2 Setup
WPA2 Setup

Next, choose whether or not an IPv4 address should be configured on the Ethernet or wireless interface:

圖形 2.35. Choose IPv4 Networking
Choose IPv4 Networking

There are two methods of IPv4 configuration. DHCP will automatically configure the network interface correctly and should be used if the network provides a DHCP server. Otherwise, the addressing information needs to be input manually as a static configuration.

注意:

Do not enter random network information as it will not work. If a DHCP server is not available, obtain the information listed in 需要的網路資訊 from the network administrator or Internet service provider.

If a DHCP server is available, select [ Yes ] in the next menu to automatically configure the network interface. The installer will appear to pause for a minute or so as it finds the DHCP server and obtains the addressing information for the system.

圖形 2.36. Choose IPv4 DHCP Configuration
Choose IPv4 DHCP Configuration

If a DHCP server is not available, select [ No ] and input the following addressing information in this menu:

圖形 2.37. IPv4 Static Configuration
IPv4 Static Configuration

  • IP Address - The IPv4 address assigned to this computer. The address must be unique and not already in use by another piece of equipment on the local network.

  • Subnet Mask - The subnet mask for the network.

  • Default Router - The IP address of the network's default gateway.

The next screen will ask if the interface should be configured for IPv6. If IPv6 is available and desired, choose [ Yes ] to select it.

圖形 2.38. Choose IPv6 Networking
Choose IPv6 Networking

IPv6 also has two methods of configuration. StateLess Address AutoConfiguration (SLAAC) will automatically request the correct configuration information from a local router. Refer to http://tools.ietf.org/html/rfc4862 for more information. Static configuration requires manual entry of network information.

If an IPv6 router is available, select [ Yes ] in the next menu to automatically configure the network interface. The installer will appear to pause for a minute or so as it finds the router and obtains the addressing information for the system.

圖形 2.39. Choose IPv6 SLAAC Configuration
Choose IPv6 SLAAC Configuration

If an IPv6 router is not available, select [ No ] and input the following addressing information in this menu:

圖形 2.40. IPv6 Static Configuration
IPv6 Static Configuration

  • IPv6 Address - The IPv6 address assigned to this computer. The address must be unique and not already in use by another piece of equipment on the local network.

  • Default Router - The IPv6 address of the network's default gateway.

The last network configuration menu is used to configure the Domain Name System (DNS) resolver, which converts hostnames to and from network addresses. If DHCP or SLAAC was used to autoconfigure the network interface, the Resolver Configuration values may already be filled in. Otherwise, enter the local network's domain name in the Search field. DNS #1 and DNS #2 are the IPv4 and/or IPv6 addresses of the DNS servers. At least one DNS server is required.

圖形 2.41. DNS Configuration
DNS Configuration

2.8.3. 設定時區

The next menu asks if the system clock uses UTC or local time. When in doubt, select [ No ] to choose the more commonly-used local time.

圖形 2.42. Select Local or UTC Clock
Select Local or UTC Clock

The next series of menus are used to determine the correct local time by selecting the geographic region, country, and time zone. Setting the time zone allows the system to automatically correct for regional time changes, such as daylight savings time, and perform other time zone related functions properly.

The example shown here is for a machine located in the Eastern time zone of the United States. The selections will vary according to the geographical location.

圖形 2.43. 選擇區域
選擇區域

The appropriate region is selected using the arrow keys and then pressing Enter.

圖形 2.44. 選擇國家
選擇國家

Select the appropriate country using the arrow keys and press Enter.

圖形 2.45. 選擇時區
選擇時區

使用方向鍵選擇適當的時區,並按下 Enter

圖形 2.46. 確認時區
確認時區

Confirm the abbreviation for the time zone is correct. If it is, press Enter to continue with the post-installation configuration.

2.8.4. 開啟服務

The next menu is used to configure which system services will be started whenever the system boots. All of these services are optional. Only start the services that are needed for the system to function.

圖形 2.47. Selecting Additional Services to Enable
Selecting Additional Services to Enable

Here is a summary of the services which can be enabled in this menu:

  • sshd - The Secure Shell (SSH) daemon is used to remotely access a system over an encrypted connection. Only enable this service if the system should be available for remote logins.

  • moused - Enable this service if the mouse will be used from the command-line system console.

  • ntpd - The Network Time Protocol (NTP) daemon for automatic clock synchronization. Enable this service if there is a Windows®, Kerberos, or LDAP server on the network.

  • powerd - System power control utility for power control and energy saving.

2.8.5. Enabling Crash Dumps

The next menu is used to configure whether or not crash dumps should be enabled. Enabling crash dumps can be useful in debugging issues with the system, so users are encouraged to enable crash dumps.

圖形 2.48. Enabling Crash Dumps
Enabling Crash Dumps

2.8.6. 加入使用者

The next menu prompts to create at least one user account. It is recommended to login to the system using a user account rather than as root. When logged in as root, there are essentially no limits or protection on what can be done. Logging in as a normal user is safer and more secure.

Select [ Yes ] to add new users.

圖形 2.49. 加入使用者帳號
加入使用者帳號

Follow the prompts and input the requested information for the user account. The example shown in 圖形 2.50, “輸入使用者資訊” creates the asample user account.

圖形 2.50. 輸入使用者資訊
輸入使用者資訊

Here is a summary of the information to input:

  • Username - The name the user will enter to log in. A common convention is to use the first letter of the first name combined with the last name, as long as each username is unique for the system. The username is case sensitive and should not contain any spaces.

  • Full name - The user's full name. This can contain spaces and is used as a description for the user account.

  • Uid - User ID. Typically, this is left blank so the system will assign a value.

  • Login group - The user's group. Typically this is left blank to accept the default.

  • Invite user into other groups? - Additional groups to which the user will be added as a member. If the user needs administrative access, type wheel here.

  • Login class - Typically left blank for the default.

  • Shell - Type in one of the listed values to set the interactive shell for the user. Refer to 節 3.10, “Shells” for more information about shells.

  • Home directory - The user's home directory. The default is usually correct.

  • Home directory permissions - Permissions on the user's home directory. The default is usually correct.

  • Use password-based authentication? - Typically yes so that the user is prompted to input their password at login.

  • Use an empty password? - Typically no as it is insecure to have a blank password.

  • Use a random password? - Typically no so that the user can set their own password in the next prompt.

  • Enter password - The password for this user. Characters typed will not show on the screen.

  • Enter password again - The password must be typed again for verification.

  • Lock out the account after creation? - Typically no so that the user can login.

After entering everything, a summary is shown for review. If a mistake was made, enter no and try again. If everything is correct, enter yes to create the new user.

圖形 2.51. 離開使用者和群組管理
離開使用者和群組管理

If there are more users to add, answer the Add another user? question with yes. Enter no to finish adding users and continue the installation.

For more information on adding users and user management, see 節 3.3, “Users and Basic Account Management”.

2.8.7. 最後設定

After everything has been installed and configured, a final chance is provided to modify settings.

圖形 2.52. 最後設定
最後設定

Use this menu to make any changes or do any additional configuration before completing the installation.

After any final configuration is complete, select Exit.

圖形 2.53. Manual Configuration
Manual Configuration

bsdinstall will prompt if there are any additional configuration that needs to be done before rebooting into the new system. Select [ Yes ] to exit to a shell within the new system or [ No ] to proceed to the last step of the installation.

圖形 2.54. Complete the Installation
Complete the Installation

If further configuration or special setup is needed, select [ Live CD ] to boot the install media into Live CD mode.

If the installation is complete, select [ Reboot ] to reboot the computer and start the new FreeBSD system. Do not forget to remove the FreeBSD install media or the computer may boot from it again.

As FreeBSD boots, informational messages are displayed. After the system finishes booting, a login prompt is displayed. At the login: prompt, enter the username added during the installation. Avoid logging in as root. Refer to 節 3.3.1.3, “The Superuser Account” for instructions on how to become the superuser when administrative access is needed.

The messages that appeared during boot can be reviewed by pressing Scroll-Lock to turn on the scroll-back buffer. The PgUp, PgDn, and arrow keys can be used to scroll back through the messages. When finished, press Scroll-Lock again to unlock the display and return to the console. To review these messages once the system has been up for some time, type less /var/run/dmesg.boot from a command prompt. Press q to return to the command line after viewing.

If sshd was enabled in 圖形 2.47, “Selecting Additional Services to Enable”, the first boot may be a bit slower as the system will generate the RSA and DSA keys. Subsequent boots will be faster. The fingerprints of the keys will be displayed, as seen in this example:

Generating public/private rsa1 key pair.
Your identification has been saved in /etc/ssh/ssh_host_key.
Your public key has been saved in /etc/ssh/ssh_host_key.pub.
The key fingerprint is:
10:a0:f5:af:93:ae:a3:1a:b2:bb:3c:35:d9:5a:b3:f3 root@machine3.example.com
The key's randomart image is:
+--[RSA1 1024]----+
|    o..          |
|   o . .         |
|  .   o          |
|       o         |
|    o   S        |
|   + + o         |
|o . + *          |
|o+ ..+ .         |
|==o..o+E         |
+-----------------+
Generating public/private dsa key pair.
Your identification has been saved in /etc/ssh/ssh_host_dsa_key.
Your public key has been saved in /etc/ssh/ssh_host_dsa_key.pub.
The key fingerprint is:
7e:1c:ce:dc:8a:3a:18:13:5b:34:b5:cf:d9:d1:47:b2 root@machine3.example.com
The key's randomart image is:
+--[ DSA 1024]----+
|       ..     . .|
|      o  .   . + |
|     . ..   . E .|
|    . .  o o . . |
|     +  S = .    |
|    +  . = o     |
|     +  . * .    |
|    . .  o .     |
|      .o. .      |
+-----------------+
Starting sshd.

Refer to 節 13.8, “OpenSSH” for more information about fingerprints and SSH.

FreeBSD does not install a graphical environment by default. Refer to 章 5, X Window 視窗系統 for more information about installing and configuring a graphical window manager.

Proper shutdown of a FreeBSD computer helps protect data and hardware from damage. Do not turn off the power before the system has been properly shut down! If the user is a member of the wheel group, become the superuser by typing su at the command line and entering the root password. Then, type shutdown -p now and the system will shut down cleanly, and if the hardware supports it, turn itself off.

2.9. 故障排除

This section covers basic installation troubleshooting, such as common problems people have reported.

Check the Hardware Notes (http://www.freebsd.org/releases/index.html) document for the version of FreeBSD to make sure the hardware is supported. If the hardware is supported and lock-ups or other problems occur, build a custom kernel using the instructions in 章 8, 設定 FreeBSD Kernel to add support for devices which are not present in the GENERIC kernel. The default kernel assumes that most hardware devices are in their factory default configuration in terms of IRQs, I/O addresses, and DMA channels. If the hardware has been reconfigured, a custom kernel configuration file can tell FreeBSD where to find things.

注意:

Some installation problems can be avoided or alleviated by updating the firmware on various hardware components, most notably the motherboard. Motherboard firmware is usually referred to as the BIOS. Most motherboard and computer manufacturers have a website for upgrades and upgrade information.

Manufacturers generally advise against upgrading the motherboard BIOS unless there is a good reason for doing so, like a critical update. The upgrade process can go wrong, leaving the BIOS incomplete and the computer inoperative.

If the system hangs while probing hardware during boot, or it behaves strangely during install, ACPI may be the culprit. FreeBSD makes extensive use of the system ACPI service on the i386, amd64, and ia64 platforms to aid in system configuration if it is detected during boot. Unfortunately, some bugs still exist in both the ACPI driver and within system motherboards and BIOS firmware. ACPI can be disabled by setting the hint.acpi.0.disabled hint in the third stage boot loader:

set hint.acpi.0.disabled="1"

This is reset each time the system is booted, so it is necessary to add hint.acpi.0.disabled="1" to the file /boot/loader.conf. More information about the boot loader can be found in 節 12.1, “概述”.

2.10. 使用 Live CD

The welcome menu of bsdinstall, shown in 圖形 2.3, “歡迎選單”, provides a [ Live CD ] option. This is useful for those who are still wondering whether FreeBSD is the right operating system for them and want to test some of the features before installing.

The following points should be noted before using the [ Live CD ]:

  • To gain access to the system, authentication is required. The username is root and the password is blank.

  • As the system runs directly from the installation media, performance will be significantly slower than that of a system installed on a hard disk.

  • This option only provides a command prompt and not a graphical interface.

章 3. UNIX 基礎概念

3.1. 概述

接下來的這一章將涵蓋 FreeBSD 作業系統的基本指令及功能。 大部份的內容在 UNIX®-like 作業系統中都是相通的。 如果您對這些內容熟悉的話,可以放心的跳過。 如果您剛接觸 FreeBSD,那您一定要仔細的讀完這章。

讀完這章,您將了解:

  • 如何使用 FreeBSD 的virtual consoles

  • UNIX® 檔案權限運作的方式以及 FreeBSD 中檔案的 flags。

  • 預設的 FreeBSD 檔案系統配置。

  • FreeBSD 的磁碟結構。

  • 如何掛載(mount)、卸載(umount)檔案系統

  • 什麼是processes、daemons 以及 signals 。

  • 什麼是 shell ,以及如何變更您預設的登入環境。

  • 如何使用基本的文字編輯器。

  • 什麼是 devices 和 device nodes 。

  • FreeBSD 下使用的 binary 格式。

  • 如何閱讀 manual pages 以獲得更多的資訊。

3.2. Virtual Consoles 和終端機

有很多方法可以操作 FreeBSD ,其中一種就是在文字終端機上打字。 如此使用 FreeBSD 即可輕易的體會到 UNIX® 作業系統的威力和彈性。 這一節描述什麼是終端機console ,以及可以如何在 FreeBSD 中運用它們。

3.2.1. The Console

如果您沒有將 FreeBSD 設定成開機時自動進入圖形化模式,系統會在啟動的 script 跑完之後顯示登入的提示符號。 您將會看到像是這樣的東西:

Additional ABI support:.
Local package initialization:.
Additional TCP options:.

Fri Sep 20 13:01:06 EEST 2002

FreeBSD/i386 (pc3.example.org) (ttyv0)

login:

這個訊息在您的系統上會有些許的不同,但是應該會看到類似的東西。 我們感興趣的是最後兩行,最後兩行是:

FreeBSD/i386 (pc3.example.org) (ttyv0)

這行包含了剛開機完系統的資訊。 您看到的是在 Intel 或相容處理器的 x86 架構上執行的 FreeBSD的 console[1]。 這台機器的名字(每台 UNIX® 機器都有一個名字)是 pc3.example.org,而您現在看到的是它的系統 console—— ttyv0終端機。

最後的一行應該都會是:

login:

這是您應該要輸入您的帳號名稱的地方。 下一小節將告訴您如何登入 FreeBSD。

3.2.2. 登入 FreeBSD

FreeBSD 是一個 multiuser、multiprocessing 的系統。 這是一個正式的名稱,指的是在單一機器上可以同時被不同人使用, 但同時可以執行很多程式的系統。

每一種多使用者系統都需要可以分辨不同使用者的方法。 在 FreeBSD (以及所有的 UNIX®-like 作業系統) 中,所有的使用者在執行程式之前必須先登入系統。 每個使用者都有一組獨特的帳號名稱 (username)及密碼(password)。 FreeBSD 在允許使用者執行程式前將會先問這兩個問題。

在 FreeBSD 開機並跑完啟動的 script 之後[2],它將會印出提示字元要求您輸入正確的帳號名稱:

login:

在這個範例裡,我們假設您的帳號是john。 在提示字元處輸入 john 並按下 Enter 。 接著您應該會看到另一個提示字元要您輸入密碼

login: john
Password:

輸入 john 的密碼,再按下 Enter。 輸入的密碼 不會顯示在螢幕上。 您不需要為此擔心,這樣做是為了安全上的問題。

如果您輸入了正確的密碼,您應該已經登入 FreeBSD。 現在就可以嘗試所有可用的指令了。

您應該會看到MOTD (即今日訊息、Messages Of The Day),後面接著命令提示字元 (一個 #,$, 或是 % 字元)。 這就表示您已經成功登入 FreeBSD 了。

3.2.3. 多重 Console

在一個 Console 下執行 UNIX® 當然是沒有問題,然而 FreeBSD 是可以同時執行很多程式的。 像 FreeBSD 這樣可以同時執行一大堆程式的作業系統,只有一個 console 可以輸入指令實在是有點浪費。 因此 virtual consoles 就顯得相當好用。

可以設定讓 FreeBSD 同時有很多 virtual console, 用幾個按鍵的組合就可以從一個 virtual console 跳到別的 virtual console 。 每一個 console 都有自已不同的輸出頻道,當從某一個 virtual console 切換到下一個的時候,FreeBSD 會自動處理鍵盤輸入及螢幕輸出。

FreeBSD 保留了特別的按鍵組合來切換 console [3]。 您可以用 Alt+F1Alt+F2、到 Alt+F8 來切換 FreeBSD 的不同 console。

當您從一個 console 切換到下一個的時候,FreeBSD 會處理螢幕輸出的儲存及回復。 這就好像有很多虛擬的螢幕和鍵盤, 可以讓您輸入指令到 FreeBSD 執行。 在某一個 console 上執行的程式並不會因為切到別的 console 而停止執行,切換到另一個 console 時,它們仍會繼續執行。

3.2.4. /etc/ttys

FreeBSD 預設的虛擬 console 總共有 8 個, 但這並非硬性規定,您可輕鬆設定這些虛擬 console 的數量增減。 有關虛擬 console 的編號跟設定都在 /etc/ttys 這檔案內設定。

可以用 /etc/ttys 檔案來設定 FreeBSD 的虛擬 console。 檔案內每行非註解文字(該行開頭沒有 # 這字)都是設定終端機或虛擬 console。 FreeBSD 預設有 9 個虛擬 console 但只啟動 8 個,也就是以下以 ttyv 開頭的那幾行設定。

# name  getty                           type    status          comments
#
ttyv0   "/usr/libexec/getty Pc"         cons25  on  secure
# Virtual terminals
ttyv1   "/usr/libexec/getty Pc"         cons25  on  secure
ttyv2   "/usr/libexec/getty Pc"         cons25  on  secure
ttyv3   "/usr/libexec/getty Pc"         cons25  on  secure
ttyv4   "/usr/libexec/getty Pc"         cons25  on  secure
ttyv5   "/usr/libexec/getty Pc"         cons25  on  secure
ttyv6   "/usr/libexec/getty Pc"         cons25  on  secure
ttyv7   "/usr/libexec/getty Pc"         cons25  on  secure
ttyv8   "/usr/X11R6/bin/xdm -nodaemon"  xterm   off secure

有關各欄位的設定以及其他選項,請參閱 ttys(5) 說明。

3.2.5. Single User 模式的 Console

有關 single user 模式 的介紹在 節 12.6.2, “Single-User Mode” 這邊有詳盡介紹。 在 single user 模式時,能夠使用的 console 只有一個,並無虛擬 console 可用。 而 single user 模式相關設定值可以在 /etc/ttys 檔做調整。 下面以 console 開頭的那行,就是了:

# name  getty                           type    status          comments
#
# If console is marked "insecure", then init will ask for the root password
# when going to single-user mode.
console none                            unknown off secure

注意:

console 那行前面的註解有提到,可以把那行的 secure 改為 insecure, 如此一來,即使 FreeBSD 進入 single user 模式, 仍會要求您輸入 root 的密碼。

請審慎考慮是否要改為 insecure。 因為萬一忘記 root 密碼的話,若要登入 single user 模式就有些麻煩了。儘管還有其他方式可以登入,但對不熟 FreeBSD 開機程序的人而言,就會相當棘手。

3.2.6. 更改 console 的顯示畫面

FreeBSD console 預設顯示大小可以調整為 1024x768、1280x1024 或其他顯示卡與螢幕有支援的解析度大小。 要切換顯示大小,必須要重新編譯 kernel 並加入下面這兩項設定:

options VESA
options SC_PIXEL_MODE

一旦 kernel 有加入這兩項並重新編譯完畢,就可以用 vidcontrol(1) 來偵測目前所支援的模式有哪些。 若要查看支援的模式,可以打:

# vidcontrol -i mode

該指令會顯示該機器所支援的顯示模式清單。 然後可以在 root console 內透過 vidcontrol(1) 指令, 來更改顯示模式:

# vidcontrol MODE_279

若對新的顯示模式覺得還不錯,可以在 /etc/rc.conf 設定之,以讓每次重開機後會自動生效。 以上面這情況為例,就是:

allscreens_flags="MODE_279"

3.3. Users and Basic Account Management

FreeBSD allows multiple users to use the computer at the same time. While only one user can sit in front of the screen and use the keyboard at any one time, any number of users can log in to the system through the network. To use the system, each user should have their own user account.

This chapter describes:

  • The different types of user accounts on a FreeBSD system.

  • How to add, remove, and modify user accounts.

  • How to set limits to control the resources that users and groups are allowed to access.

  • How to create groups and add users as members of a group.

3.3.1. Account Types

Since all access to the FreeBSD system is achieved using accounts and all processes are run by users, user and account management is important.

There are three main types of accounts: system accounts, user accounts, and the superuser account.

3.3.1.1. System Accounts

System accounts are used to run services such as DNS, mail, and web servers. The reason for this is security; if all services ran as the superuser, they could act without restriction.

Examples of system accounts are daemon, operator, bind, news, and www.

nobody is the generic unprivileged system account. However, the more services that use nobody, the more files and processes that user will become associated with, and hence the more privileged that user becomes.

3.3.1.2. User Accounts

User accounts are assigned to real people and are used to log in and use the system. Every person accessing the system should have a unique user account. This allows the administrator to find out who is doing what and prevents users from clobbering the settings of other users.

Each user can set up their own environment to accommodate their use of the system, by configuring their default shell, editor, key bindings, and language settings.

Every user account on a FreeBSD system has certain information associated with it:

User name

The user name is typed at the login: prompt. Each user must have a unique user name. There are a number of rules for creating valid user names which are documented in passwd(5). It is recommended to use user names that consist of eight or fewer, all lower case characters in order to maintain backwards compatibility with applications.

Password

Each account has an associated password.

User ID (UID)

The User ID (UID) is a number used to uniquely identify the user to the FreeBSD system. Commands that allow a user name to be specified will first convert it to the UID. It is recommended to use a UID less than 65535, since higher values may cause compatibility issues with some software.

Group ID (GID)

The Group ID (GID) is a number used to uniquely identify the primary group that the user belongs to. Groups are a mechanism for controlling access to resources based on a user's GID rather than their UID. This can significantly reduce the size of some configuration files and allows users to be members of more than one group. It is recommended to use a GID of 65535 or lower as higher GIDs may break some software.

Login class

Login classes are an extension to the group mechanism that provide additional flexibility when tailoring the system to different users. Login classes are discussed further in 節 13.13.1, “Configuring Login Classes”.

Password change time

By default, passwords do not expire. However, password expiration can be enabled on a per-user basis, forcing some or all users to change their passwords after a certain amount of time has elapsed.

Account expiry time

By default, FreeBSD does not expire accounts. When creating accounts that need a limited lifespan, such as student accounts in a school, specify the account expiry date using pw(8). After the expiry time has elapsed, the account cannot be used to log in to the system, although the account's directories and files will remain.

User's full name

The user name uniquely identifies the account to FreeBSD, but does not necessarily reflect the user's real name. Similar to a comment, this information can contain spaces, uppercase characters, and be more than 8 characters long.

Home directory

The home directory is the full path to a directory on the system. This is the user's starting directory when the user logs in. A common convention is to put all user home directories under /home/username or /usr/home/username. Each user stores their personal files and subdirectories in their own home directory.

User shell

The shell provides the user's default environment for interacting with the system. There are many different kinds of shells and experienced users will have their own preferences, which can be reflected in their account settings.

3.3.1.3. The Superuser Account

The superuser account, usually called root, is used to manage the system with no limitations on privileges. For this reason, it should not be used for day-to-day tasks like sending and receiving mail, general exploration of the system, or programming.

The superuser, unlike other user accounts, can operate without limits, and misuse of the superuser account may result in spectacular disasters. User accounts are unable to destroy the operating system by mistake, so it is recommended to login as a user account and to only become the superuser when a command requires extra privilege.

Always double and triple-check any commands issued as the superuser, since an extra space or missing character can mean irreparable data loss.

There are several ways to gain superuser privilege. While one can log in as root, this is highly discouraged.

Instead, use su(1) to become the superuser. If - is specified when running this command, the user will also inherit the root user's environment. The user running this command must be in the wheel group or else the command will fail. The user must also know the password for the root user account.

In this example, the user only becomes superuser in order to run make install as this step requires superuser privilege. Once the command completes, the user types exit to leave the superuser account and return to the privilege of their user account.

範例 3.1. Install a Program As the Superuser
% configure
% make
% su -
Password:
# make install
# exit
%

The built-in su(1) framework works well for single systems or small networks with just one system administrator. An alternative is to install the security/sudo package or port. This software provides activity logging and allows the administrator to configure which users can run which commands as the superuser.

3.3.2. Managing Accounts

FreeBSD provides a variety of different commands to manage user accounts. The most common commands are summarized in 表格 3.1, “Utilities for Managing User Accounts”, followed by some examples of their usage. See the manual page for each utility for more details and usage examples.

表格 3.1. Utilities for Managing User Accounts
CommandSummary
adduser(8)The recommended command-line application for adding new users.
rmuser(8)The recommended command-line application for removing users.
chpass(1)A flexible tool for changing user database information.
passwd(1)The command-line tool to change user passwords.
pw(8)A powerful and flexible tool for modifying all aspects of user accounts.

3.3.2.1. adduser

The recommended program for adding new users is adduser(8). When a new user is added, this program automatically updates /etc/passwd and /etc/group. It also creates a home directory for the new user, copies in the default configuration files from /usr/share/skel, and can optionally mail the new user a welcome message. This utility must be run as the superuser.

The adduser(8) utility is interactive and walks through the steps for creating a new user account. As seen in 範例 3.2, “Adding a User on FreeBSD”, either input the required information or press Return to accept the default value shown in square brackets. In this example, the user has been invited into the wheel group, allowing them to become the superuser with su(1). When finished, the utility will prompt to either create another user or to exit.

範例 3.2. Adding a User on FreeBSD
# adduser
Username: jru
Full name: J. Random User
Uid (Leave empty for default):
Login group [jru]:
Login group is jru. Invite jru into other groups? []: wheel
Login class [default]:
Shell (sh csh tcsh zsh nologin) [sh]: zsh
Home directory [/home/jru]:
Home directory permissions (Leave empty for default):
Use password-based authentication? [yes]:
Use an empty password? (yes/no) [no]:
Use a random password? (yes/no) [no]:
Enter password:
Enter password again:
Lock out the account after creation? [no]:
Username   : jru
Password   : ****
Full Name  : J. Random User
Uid        : 1001
Class      :
Groups     : jru wheel
Home       : /home/jru
Shell      : /usr/local/bin/zsh
Locked     : no
OK? (yes/no): yes
adduser: INFO: Successfully added (jru) to the user database.
Add another user? (yes/no): no
Goodbye!
#

注意:

Since the password is not echoed when typed, be careful to not mistype the password when creating the user account.

3.3.2.2. rmuser

To completely remove a user from the system, run rmuser(8) as the superuser. This command performs the following steps:

  1. Removes the user's crontab(1) entry, if one exists.

  2. Removes any at(1) jobs belonging to the user.

  3. Kills all processes owned by the user.

  4. Removes the user from the system's local password file.

  5. Optionally removes the user's home directory, if it is owned by the user.

  6. Removes the incoming mail files belonging to the user from /var/mail.

  7. Removes all files owned by the user from temporary file storage areas such as /tmp.

  8. Finally, removes the username from all groups to which it belongs in /etc/group. If a group becomes empty and the group name is the same as the username, the group is removed. This complements the per-user unique groups created by adduser(8).

rmuser(8) cannot be used to remove superuser accounts since that is almost always an indication of massive destruction.

By default, an interactive mode is used, as shown in the following example.

範例 3.3. rmuser Interactive Account Removal
# rmuser jru
Matching password entry:
jru:*:1001:1001::0:0:J. Random User:/home/jru:/usr/local/bin/zsh
Is this the entry you wish to remove? y
Remove user's home directory (/home/jru)? y
Removing user (jru): mailspool home passwd.
#

3.3.2.3. chpass

Any user can use chpass(1) to change their default shell and personal information associated with their user account. The superuser can use this utility to change additional account information for any user.

When passed no options, aside from an optional username, chpass(1) displays an editor containing user information. When the user exits from the editor, the user database is updated with the new information.

注意:

This utility will prompt for the user's password when exiting the editor, unless the utility is run as the superuser.

In 範例 3.4, “Using chpass as Superuser”, the superuser has typed chpass jru and is now viewing the fields that can be changed for this user. If jru runs this command instead, only the last six fields will be displayed and available for editing. This is shown in 範例 3.5, “Using chpass as Regular User”.

範例 3.4. Using chpass as Superuser
#Changing user database information for jru.
Login: jru
Password: *
Uid [#]: 1001
Gid [# or name]: 1001
Change [month day year]:
Expire [month day year]:
Class:
Home directory: /home/jru
Shell: /usr/local/bin/zsh
Full Name: J. Random User
Office Location:
Office Phone:
Home Phone:
Other information:

範例 3.5. Using chpass as Regular User
#Changing user database information for jru.
Shell: /usr/local/bin/zsh
Full Name: J. Random User
Office Location:
Office Phone:
Home Phone:
Other information:

注意:

The commands chfn(1) and chsh(1) are links to chpass(1), as are ypchpass(1), ypchfn(1), and ypchsh(1). Since NIS support is automatic, specifying the yp before the command is not necessary. How to configure NIS is covered in 章 28, 網路伺服器.

3.3.2.4. passwd

Any user can easily change their password using passwd(1). To prevent accidental or unauthorized changes, this command will prompt for the user's original password before a new password can be set:

範例 3.6. Changing Your Password
% passwd
Changing local password for jru.
Old password:
New password:
Retype new password:
passwd: updating the database...
passwd: done

The superuser can change any user's password by specifying the username when running passwd(1). When this utility is run as the superuser, it will not prompt for the user's current password. This allows the password to be changed when a user cannot remember the original password.

範例 3.7. Changing Another User's Password as the Superuser
# passwd jru
Changing local password for jru.
New password:
Retype new password:
passwd: updating the database...
passwd: done

注意:

As with chpass(1), yppasswd(1) is a link to passwd(1), so NIS works with either command.

3.3.2.5. pw

The pw(8) utility can create, remove, modify, and display users and groups. It functions as a front end to the system user and group files. pw(8) has a very powerful set of command line options that make it suitable for use in shell scripts, but new users may find it more complicated than the other commands presented in this section.

3.3.3. Managing Groups

A group is a list of users. A group is identified by its group name and GID. In FreeBSD, the kernel uses the UID of a process, and the list of groups it belongs to, to determine what the process is allowed to do. Most of the time, the GID of a user or process usually means the first group in the list.

The group name to GID mapping is listed in /etc/group. This is a plain text file with four colon-delimited fields. The first field is the group name, the second is the encrypted password, the third the GID, and the fourth the comma-delimited list of members. For a more complete description of the syntax, refer to group(5).

The superuser can modify /etc/group using a text editor. Alternatively, pw(8) can be used to add and edit groups. For example, to add a group called teamtwo and then confirm that it exists:

範例 3.8. Adding a Group Using pw(8)
# pw groupadd teamtwo
# pw groupshow teamtwo
teamtwo:*:1100:

In this example, 1100 is the GID of teamtwo. Right now, teamtwo has no members. This command will add jru as a member of teamtwo.

範例 3.9. Adding User Accounts to a New Group Using pw(8)
# pw groupmod teamtwo -M jru
# pw groupshow teamtwo
teamtwo:*:1100:jru

The argument to -M is a comma-delimited list of users to be added to a new (empty) group or to replace the members of an existing group. To the user, this group membership is different from (and in addition to) the user's primary group listed in the password file. This means that the user will not show up as a member when using groupshow with pw(8), but will show up when the information is queried via id(1) or a similar tool. When pw(8) is used to add a user to a group, it only manipulates /etc/group and does not attempt to read additional data from /etc/passwd.

範例 3.10. Adding a New Member to a Group Using pw(8)
# pw groupmod teamtwo -m db
# pw groupshow teamtwo
teamtwo:*:1100:jru,db

In this example, the argument to -m is a comma-delimited list of users who are to be added to the group. Unlike the previous example, these users are appended to the group and do not replace existing users in the group.

範例 3.11. Using id(1) to Determine Group Membership
% id jru
uid=1001(jru) gid=1001(jru) groups=1001(jru), 1100(teamtwo)

In this example, jru is a member of the groups jru and teamtwo.

For more information about this command and the format of /etc/group, refer to pw(8) and group(5).

3.4. 權限

FreeBSD 源自於 BSD UNIX®,繼承了幾個重要的 UNIX® 概念。 首先也最明顯,它是一款 multi-user 作業系統。 它可以同時處理多人多工, 負責徹底的分享與管理來自每位使用者對硬碟裝置、週邊設備、記憶體及 CPU 時間的要求。

也因為系統能夠支援多使用者, 所以系統管理的一切都有權限來決定誰可以讀取、寫入或執行資源。 這些權限分別使用三組八進位的數字儲存,一組代表檔案的所有者, 一組代表檔案所屬的群組,而最後一組則代表其他所有人。 表示這些數字的方式如下:

權限目錄顯示
0不可讀取, 不可寫入, 不可執行---
1不可讀取, 不可寫入, 可執行--x
2不可讀取, 可寫入, 不可執行-w-
3不可讀取, 可寫入, 可執行-wx
4可讀取, 不可寫入, 不可執行r--
5可讀取, 不可寫入, 可執行r-x
6可讀取, 可寫入, 不可執行rw-
7可讀取, 可寫入, 可執行rwx

使用 ls(1) 指令時,可以加上 -l 參數, 來檢視詳細的目錄清單。 清單中欄位的資訊包含檔案對所有者、群組及其他人的權限。 在任一個目錄底下執行 ls -l,會顯示如下的結果:

% ls -l
total 530
-rw-r--r--  1 root  wheel     512 Sep  5 12:31 myfile
-rw-r--r--  1 root  wheel     512 Sep  5 12:31 otherfile
-rw-r--r--  1 root  wheel    7680 Sep  5 12:31 email.txt
...

在這裡告所您該如何區分 ls -l 第一欄當中的資訊:

-rw-r--r--

第一個 (最左邊) 的字元用來表示這個檔案的類型為何, 除標準檔案以外,尚有目錄、特殊字元裝置 (Special character device)、 Socket 及其他特殊虛擬檔案裝置 (Special pseudo-file device), 在此例當中,- 表示該檔案為一個標準的檔案。 範例中接下來的三個字元中,rw- 代表所有者對檔案擁有的權限。 再接下來的三個字元, r-- 則代表群組對檔案擁有的權限, 最後三個字元,r-- 則代表其他人對檔案擁有的權限。 破折號 (-) 表示沒有權限,範例中的這個檔案的權限, 只允許所有者讀取、寫入檔案,群組以及其他人僅能讀取檔案。 根據以上的表格,此種權限的檔案可以使用 644 來表示, 每組數字分別代表檔案的三種權限。

以上是不錯的方式,但系統該如何控制裝置的權限? 實際上 FreeBSD 對大多的硬碟裝置就如同檔案,程式可以開啟、讀取以及寫入資料如一般檔案。 這些特殊裝置檔案 (Special device file) 都儲存於 /dev 目錄中。

目錄也同如檔案,擁有讀取、寫入及執行的權限, 但在執行權限上與檔案有明顯的差異。 當目錄被標示為可執行時,代表可以使用 cd (更改目錄) 進入該目錄。 也代表能夠存取在此目錄之中的已知檔名的檔案 (當然,檔案仍擁有自己的權限)

尤其,要能夠列出目錄內容,必須擁有目錄的讀取權限。 而當要刪除已知檔名的檔案時,也必須擁有檔案所在目錄的寫入 以及 執行的權限。

還有一些權限,但這些權限主要在特殊情況使用,如 setuid binaries 及 sticky directories。 如果您還想知道更多檔案權限的資訊及使用方法,請務必參閱 chmod(1) 說明文件。

3.4.1. 權限符號

Contributed by Tom Rhodes.

權限符號可稱做符號表示, 使用字元的方式來取代使用數值來設定檔案或目錄的權限。 符號表示的格式依序為 (某人)(動作)(權限),可使用的符號如下:

項目字母意義
(某人)u使用者
(某人)g群組所有者
(某人)o其他
(某人)a全部(world)
(動作)+增加權限
(動作)-移除權限
(動作)=指定權限
(權限)r讀取
(權限)w寫入
(權限)x執行
(權限)tSticky bit
(權限)sSet UID 或 GID

如先前同樣使用 chmod(1) 指令來設定,但使用的參數為這些字元。 例如,您可以使用下列指令禁止其他使用者存取檔案 FILE:

% chmod go= FILE

若有兩個以上的符號表示可以使用逗號 (,) 區隔。 例如,下列指令將會移除群組及其他人對檔案 FILE 的寫入權限, 並使全部人(world)對該檔有執行權限。

% chmod go-w,a+x FILE

3.4.2. FreeBSD 檔案旗標(Flag)

Contributed by Tom Rhodes.

除了前面提到的檔案權限外,FreeBSD 支援使用 檔案旗標。 這些旗標增加了檔案的安全性及管理性,但不包含目錄。

檔案旗標增加了管理性,確保在某些時候 root 不會意外將檔案修改或移除。

修改的檔案 flag 僅需要使用擁有簡易的介面的 chflags(1) 工具。 例如,標示系統禁止刪除的旗標於檔案 file1,使用下列指令:

# chflags sunlink file1

若要移除系統禁止刪除的旗標,只需要簡單在 sunlink 前加上 no,例如:

# chflags nosunlink file1

使用 ls(1) 及參數 -lo 可檢視檔案目前的旗標:

# ls -lo file1
	

輸出的結果如下:

-rw-r--r--  1 trhodes  trhodes  sunlnk 0 Mar  1 05:54 file1

多數的旗標僅能由 root 使用者來標示或移除,而部份旗標可由檔案所有者設定。 我們建議系統管理者可閱讀 chflags(1)chflags(2) 說明以瞭解相關細節。

3.5. 目錄結構

認識 FreeBSD 的目錄架構,就可對系統有概略的基礎理解。 最重要的莫過於整個目錄的根目錄,就是 / 目錄, 該目錄會在開機時最先掛載 (mount),裡面會有開機所會用到必備檔案。 此外,根目錄還有紀錄其他檔案系統的掛載點相關設定。

「掛載點」就是讓新增的檔案系統,能接到上層的檔案系統 (通常就是「根目錄」檔案系統) 的目錄。 在 節 3.6, “磁碟組織” 這邊對此有更詳細介紹。 標準的掛載點包括了 /usr/var/tmp/mnt 以及 /cdrom。 這些目錄通常會記錄在 /etc/fstab 設定檔內。 /etc/fstab 是記錄各檔案系統及相關掛載點的表格。 大部分在 /etc/fstab 有記錄的檔案系統,會在開機時由 rc(8) script 來自動掛載,除非它們有設定 noauto 選項。 其中細節說明可參閱 節 3.7.1, “ fstab 檔”

有關檔案系統架構的完整說明可參閱 hier(7)。 現在呢,讓我們大致先一窺常見的目錄有哪些吧。

目錄說明
/檔案系統的根目錄。
/bin/single-user、multi-user 兩種模式皆可使用的基本工具 。
/boot/作業系統開機過程會用到的程式、設定檔。
/boot/defaults/預設的開機啟動設定檔,詳情請參閱 loader.conf(5)
/dev/Device nodes,詳情請參閱 intro(4)
/etc/系統設定檔及一些 script 檔。
/etc/defaults/預設的系統設定檔,詳情請參閱 rc(8)
/etc/mail/MTA(Mail Transport Agent)的相關設定檔,像是 sendmail(8)
/etc/namedb/named 設定檔,詳情請參閱 named(8)
/etc/periodic/每日、每週、每月透過 cron(8); 執行的定期排程 script, 詳情請參閱 periodic(8)
/etc/ppp/ppp 設定檔,詳情請參閱 ppp(8)
/mnt/系統管理者慣用充當臨時掛載點的空目錄。
/proc/Process 檔案系統,詳情請參閱 procfs(5)mount_procfs(8)
/rescue/緊急救援用途的一些 statically linked 程式,詳情請參閱 rescue(8)
/root/root 帳號的家目錄。
/sbin/供 single-user 及 multi-user 環境使用的系統程式及管理工具 。
/tmp/臨時檔案。 一般而言,重開機之後 /tmp 內的東西會被清除掉。 而通常會將 memory-based 檔案系統掛載在 /tmp 上。 這些瑣事可透過 tmpmfs 相關的 rc.conf(5) 環境變數來自動完成 。(或是在 /etc/fstab 內做設定, 詳情請參閱 mdmfs(8)。)
/usr/主要是使用者所安裝的工具程式、應用程式存放處。
/usr/bin/常用工具、開發工具、應用軟體。
/usr/include/標準 C include 的相關 header 檔案庫。
/usr/lib/函式庫存放處。
/usr/libdata/其他各式工具的資料檔。
/usr/libexec/系統 daemons 及系統工具程式(透過其他程式來執行)。
/usr/local/存放一些自行安裝的執行檔、函式庫等等。 同時,也是 FreeBSD ports 架構的預設安裝目錄。 /usr/local 內的目錄架構大致與 /usr 相同,詳情請參閱 hier(7) 說明。 但 man 目錄例外,它們是直接放在 /usr/local 底下,而非 /usr/local/share,而 ports 所安裝的說明文件則在 share/doc/port
/usr/obj/在編譯 /usr/src 目錄時所產生的相關架構 object 檔案。
/usr/portsFreeBSD Ports Collection (optional)。
/usr/sbin/系統 daemon 及系統工具(直接由使用者執行)。
/usr/share/各架構皆共通的檔案。
/usr/src/BSD 本身的原始碼(或自行新增的)。
/usr/X11R6/X11R6 相關套件的執行檔、函式庫等(optional)。
/var/存放各種用途的 log 檔、臨時或暫時存放、列印或郵件的 spool 檔案。有時候,memory-based 檔案系統也會掛載在 /var。 這些瑣事可透過 varmfs 相關的 rc.conf(5) 環境變數來自動完成。(或是在 /etc/fstab 內做設定,相關細節請參閱 mdmfs(8)。)
/var/log/各項系統記錄的 log 檔案。
/var/mail/各使用者的 mailbox 檔案。
/var/spool/各種印表機、郵件系統的 spool 目錄。
/var/tmp/臨時檔案。 這些檔案在重開機後通常仍會保留,除非 /var 是屬於 memory-based 檔案系統。
/var/yp記錄 NIS maps。

3.6. 磁碟組織

FreeBSD 用來尋找檔案的最小單位就是檔案的名稱了。 檔案的名稱有大小寫之分,所以說 readme.txtREADME.TXT 是兩個不同的檔案。 FreeBSD 並不使用副檔名 (.txt) 來判別這是一個程式檔、文件檔或是其他類型的檔案。

檔案存在目錄裡面。 一個目錄中可能沒有任何檔案,也可能有好幾百個檔案。 目錄之中也可以包含其他的目錄; 您可以建立階層式的目錄以便資料的管理。

檔案或目錄的對應是藉由給定的檔案或目錄名稱,然後加上正斜線符號 (/);之後再視需要加上其他的目錄名稱。 如果您有一個目錄 foo ,裡面有一個目錄叫作 bar,這個目錄中又包含了一個叫 readme.txt 的檔案,那麼這個檔案的全名,或者說檔案的路徑就是 foo/bar/readme.txt

目錄及檔案儲存在檔案系統之中。 每個檔案系統都有唯一一個最上層的目錄,叫做根目錄 (root directory)。 然後在這個根目錄下面才能有其他的目錄。

到目前為止大概和其他您用過的的作業系統都差不多。 還是有些不一樣的地方就是了,例如 MS-DOS® 用 \ 當檔案和目錄名稱的分隔符號,而 Mac OS® 則是用 : 符號。

FreeBSD 的路徑中並沒有使用磁碟機代號或其他的磁碟名稱。 因此,您不可以使用像 c:/foo/bar/readme.txt 這樣子的檔案名稱。

相對的,在 FreeBSD 系統中有一個檔案系統被指定為根檔案系統。 根檔案系統的根目錄由 / 表示。 然後其他的檔案系統再掛載 (mount) 在根檔案系統之下。因此無論您的 FreeBSD 系統上有多少顆硬碟,每一個目錄看起來就像在同一個磁碟上。

假設您有三個檔案系統,分別叫作 ABC。 每個檔案系統都包含兩個目錄,叫做 A1A2 (依此類推得 B1B2C1C2)。

A 為主要的檔案系統;如果您用 ls 指令查看此目錄的內容,您會看到兩個子目錄: A1A2,如下所示:

一個檔案系統必須以目錄形式掛載於另一個檔案系統上。 因此,假設您將 B 掛載於 A1 之上,則 B 的根目錄就變成了 A1,而在 B 之下的任何目錄的路徑也隨之改變:

B1B2 目錄中的任何檔案必須經由路徑 /A1/B1/A1/B2 才能達到。 所有原來在 /A1 中的檔案會暫時被隱藏起來,直到 B 被「移除 (unmounted)」後才會再顯現出來。

如果 B 掛載在 A2 之上,則會變成:

上面的路徑分別為 /A2/B1/A2/B2

檔案系統可以掛在其他檔案系統的目錄之上。 延續之前的例子,C 檔案系統可以掛在檔案系統 BB1 目錄之上,如圖所示:

或者 C 直接掛載於 AA1 目錄之上:

如果您熟悉 MS-DOS® 的話,這和 join 指令很類似 (雖然不儘相同)。

一般情況下您不需要擔心這些東西。 除非您要安裝新的磁碟,不然通常在您安裝 FreeBSD 時建立好檔案系統並決定好要掛載在何處之後就不會再做任何更動了。

您完全可以使用單一的一個大的根檔案系統 (root file system) 而不建立其他的檔案系統。 這樣有好處也有有壞處。

使用多個檔案系統的好處
  • 不同的檔案系統在掛上的時候可以有不同的 掛載參數。 舉例來說,為求謹慎您可以將根檔案系統設成唯讀, 以避免不小心刪除或修改掉重要的檔案。 將使用者可寫入的檔案系統 (例如 /home) 獨立出來也可以讓他們用 nosuid 的參數掛載,此選項可以讓在這個檔案系統中執行檔的 suid/guid bits 失效,也許可以讓系統更安全。

  • FreeBSD 會自動根據您檔案系統的使用方式來做最佳的檔案配置方式。 因此,一個有很多小檔案、 常常寫入的檔案系統跟只有幾個較大的檔案的檔案系統配置是不一樣的。 如果您只有單一一個大的檔案系統,這部分就沒用了。

  • FreeBSD 的檔案系統在停電的時候很穩固。 然而,在某些重要的時候停電仍然會對檔案系統結構造成損害。 分割成許多個檔案系統的話在系統在停電後比較能夠正常啟動, 以便您在需要的時候將備份資料回存回來。

使用單一檔案系統的好處
  • 檔案系統的大小是固定的。 您當初安裝 FreeBSD 的時候應該會給定一個大小,可是後來您可能會想把空間加大。 如果沒有備份的話是很難達成的; 您必須將檔案系統重新建立為您需要的大小,然後將備份回存回來。

    重要:

    FreeBSD 的 growfs(8) 指令可以突破此限制直接變更檔案系統的大小。

檔案系統包含在分割區裡面。 因為 FreeBSD 承襲 UNIX® 架構,這邊講的分割區和一般提到的分割區 (例如 MS-DOS® 分割區) 不同。 每一個分割區由一個代號(字母)表示,從 ah。 每個分割區只能包含一個檔案系統。 因此除了說常見到用檔案系統同的掛載點來表示檔案系統外, 也可以用包含他的分割區代號來表示。

FreeBSD 也會拿磁碟空間來當 swap space。 Swap space 給 FreeBSD 當作虛擬記憶體用。 這讓您的電腦好像擁有比實際更多的記憶體。 當 FreeBSD 的記憶體用完的時候,它會把一些目前沒用到的資料移到 swap space,然後在用到的時候移回去 (同時移出部份沒用到的)。

某些分割區有慣例的使用方式如下:

分割區慣例
a通常包含根檔案系統 (root file system)
b通常是 swap space
c通常和整個 slice 的大小一樣,給一些會用到整個 slice 的工具程式 (例如硬碟壞軌檢查工具) 來使用。 一般來說您應該不會把檔案系統建立在這個分割區。
d分割區 d 曾經有代表特殊意義,但是已經不再使用。 所以現在 d 就和其他一般的分割區相同了。

每個包含有檔案系統的分割區是存在所謂的 slice 裡面。 FreeBSD 的 slice 就是指平常我們稱為分割區 (partition) 的東西。 同樣地,會這樣子稱呼也是因為 FreeBSD 的 UNIX® 色彩。 而 slice 是有編號的,從 1 號編到 4 號。

slice 號碼跟在裝置名稱後面,先接一個字母 s,然後從 1 號開始編下去。 因此 da0s1 就是指第一個 SCSI 硬碟的第一個 slice。 一個磁碟上只能有四個實體的 slice,但是在實體的 slice 中您可以塞進適當類型的邏輯 slice。 這些延伸的 slice 編號從 5 開始,所以 ad0s5 是第一個 IDE 硬碟上的第一個延伸 slice。 檔案系統在裝置 (device) 裡就是在一個 slice 之中。

Slices、dangerously dedicated 模式的實體磁碟機,以及其他包含分割區(partition) 的磁碟都是以字母 ah 的編號來表示。 編號是接在裝置名稱的後面的,因此 da0a 是磁碟機 da 上的第一個 dangerously dedicated模式之分割區。 而 ad1s3e 則是第二顆 IDE 硬碟上第三個 slice 的第五個分割區。

最後,我們就可以把系統上的每個磁碟都區分出來了。 一個磁碟的名稱會有一個代碼來表示這個磁碟的類型,接著是一個數字, 表示這是哪一個磁碟。 這邊跟 slice 每個磁碟編號從 0 開始不一樣。 常見的代碼可以參考 表格 3.2, “磁碟機代號”

當要參照一個分割區的時候,FreeBSD 會要您一併輸入包含這個分割區的 slice 及磁碟機名稱;當要參照一個 slice 的時候,也必須輸入包含這個 slice 的磁碟名稱。 怎麼做呢?首先先列出磁碟名稱,然後 s 加上 slice 編號,最後再輸入分割區字母代號。 範例可以參考 範例 3.12, “磁碟、slice 及分割區命名範例”.

範例 3.13, “磁碟的概念模型” 示範了一個基本的磁碟分布模式,相信對您有些幫助。

要安裝 FreeBSD,您必須先建置磁碟的 slice,接著於 slice 中建立要給 FreeBSD 用的分割區。 最後在這些分割區中建立檔案系統 (或 swap space) 並決定要將這些檔案系統掛載於哪裡。

表格 3.2. 磁碟機代號
代號意義
adATAPI(IDE) 磁碟機
daSCSI 直接存取磁碟機
acdATAPI(IDE) 光碟機
cdSCSI 光碟機
fd軟碟機

範例 3.12. 磁碟、slice 及分割區命名範例
名稱意義
ad0s1a第一個 IDE 硬碟 (ad0) 上第一個 slice (s1)的第一個分割區(a) 。
da1s2e第二個 SCSI 硬碟 (da1) 上第二個 slice (s2) 的第五個分割區 (e) 。

範例 3.13. 磁碟的概念模型

此圖顯示 FreeBSD 中接到系統的第一個 IDE 磁碟機內部配置圖。 假設這個磁碟的容量是 4 GB,並且包含了兩個 2 GB 的 slice (MS-DOS® 的分割區)。 第一個 slice 是 DOS 的 C: 磁碟機,第二個則安裝了 FreeBSD。 本範例的 FreeBSD 有三個分割區以及一個 swap 分割區。

這三個分割區每個都是一個檔案系統。 a 分割是根 (root) 檔案系統;分割 e/var;而 f 分割是 /usr 目錄結構。


3.7. 掛載與卸載檔案系統

檔案系統就像一顆樹。/ 就像是樹根,而 /dev/usr 以及其他在根目錄下的目錄就像是樹枝,而這些樹枝上面又還有分支,像是 /usr/local 等。

因為某些原因,我們會將一些目錄分別放在不同的檔案系統上。 如 /var 包含了可能會滿出來的 log/spool/ 等目錄以及各式各樣的暫存檔。 把根檔案系統塞到滿出來顯然不是個好主意,所以我們往往會比較傾向把 /var/ 中拉出來。

另一個常見到把某些目錄放在不同檔案系統上的理由是: 這些檔案在不同的實體或虛擬磁碟機上。 像是網路檔案系統 (Network File System) 或是光碟機。

3.7.1. fstab

/etc/fstab 裡面有設定的檔案系統會在開機 的過程中自動地被掛載 (除非該檔案系統有被加上 noauto 參數)。

/etc/fstab 檔案內容的格式如下:

device       /mount-point fstype     options      dumpfreq     passno
device

裝置名稱 (該裝置必須真的存在)。 詳情請參閱 節 17.2, “裝置名稱”.

mount-point

檔案系統要掛載到的目錄 (該目錄必須真的存在)。

fstype

檔案系統類型,這是要傳給 mount(8) 的參數。 FreeBSD 預設的檔案系統是 ufs

options

可讀可寫的檔案系統用 rw,而唯讀的檔案系統則是用 ro,後面視需要還可以加其他選項。 常見的選項如 noauto 是用在不要於開機過程中自動的掛載的檔案系統。 其他選項可參閱 mount(8) 說明。

dumpfreq

dump(8) 由此項目決定那些檔案系統需要傾印。 如果這格空白則以零為預設值。

passno

這個項目決定檔案系統檢查的順序。 對於要跳過檢查的檔案系統,它們的 passno 值要設為零。 根檔案系統的 passno 值應設為一 (因為需要比所有其他的還要先檢查),而其他的檔案系統的 passno 值應該要設得比一大。 若有多個檔案系統具有相同的 passno 值,則 fsck(8) 會試著平行地(如果可能的話)檢查這些檔案系統。

更多關於 /etc/fstab 檔案格式及選項的資訊請參閱 fstab(5) 說明文件。

3.7.2. mount 指令

mount(8) 指令是拿來掛載檔案系統用的。

基本的操作指令格式如下:

# mount device mountpoint

mount(8) 裡面有提到一大堆的選項,不過最常用的就是這些:

掛載選項
-a

/etc/fstab 裡面所有還沒有被掛載、沒有被標記成 noauto 而且沒有用 -t 排除的檔案系統掛載起來。

-d

執行所有的動作,但是不真的去呼叫掛載的 system call。 這個選項和 -v 搭配拿來推測 mount(8) 將要做什麼動作時很好用。

-f

強迫掛載不乾淨的檔案系統 (危險),或是用來強制取消寫入權限 (把檔案系統的掛載狀態從可存取變成唯讀)。

-r

用唯讀的方式掛載檔案系統。 這個選項和在 -o 選項中指定 ro (在 FreeBSD 5.2之前的版本是用 rdonly) 參數是一樣的。

-t fstype

用指定的檔案系統型態 (fstype) 來掛載指定的檔案系統,或是在有 -a 選項時只掛載指定型態的檔案系統。

預設的檔案系統是 ufs

-u

更新檔案系統的掛載選項。

-v

顯示較詳細資訊。

-w

以可存取的模式掛載檔案系統。

-o 選項後面會接著以逗號分隔的參數,例如:

noexec

不允許在這個檔案系統上執行二進位程式碼, 這也是一個蠻有用的安全選項。

nosuid

不解析檔案系統上的 setuid 或 setgid 旗標, 這也是一個蠻有用的安全選項。

3.7.3. umount 指令

umount(8) 指令的參數可以是掛載點 (mountpoint),裝置名稱,以及 -a 或是 -A 等選項。

加上 -f 可以強制卸載,加上 -v 則是會顯示詳細資訊。 要注意的是一般來說用 -f 並不是個好主意,強制卸載檔案系統有可能會造成電腦當機, 或者損壞檔案系統內的資料。

-a-A 是用來卸載所有已掛載的檔案系統,另外還可以用 -t 來指定要卸載的是哪些種類的檔案系統。 要注意的是 -A 並不會試圖卸載根檔案系統。

3.8. 程序

FreeBSD 是一個多工的作業系統,也就是說在同一時間內可以跑超過一個程式。 每一個正在花時間跑的程式就叫做 程序 (process)。 您下的每個指令都至少會開啟一個新的程序, 而有些系統程序是一直在跑以維持系統正常運作的。

每一個程序都有一個不重覆的數字叫做 process ID ,或稱為 PID ,而且就像檔案一樣,每一個程序也有擁有者及群組。 擁有者及群組的資訊是用來決定什麼檔案或裝置是這個程序可以開啟的 (前面有提到過檔案權限)。 大部份的程序都有父程序。 父程序是開啟這個程序的程序,例如:您對 shell 輸入指令,shell 本身就是一個程序,而您執行的指令也是程序。 每一個您用這種方式跑的程序的父程序都是 shell。 有一個特別的程序叫做 init(8) 是個例外。init 永遠是第一個程序,所以他的 PID 一直都會是 1。 在 FreeBSD 開機的時候 init 會自動地被 kernel 開啟。

要看系統執行中的程序,有兩個相當有用的指令可用: ps(1) 以及 top(1)ps 指令是用來列出正在執行之程序,而且可以秀它們的 PID、用了多少記憶體、執行的指令名稱及其後之參數是什麼等等。 top 指令則是顯示所有正在執行的程序, 並且數秒鐘更新一次。因此您可以互動式的觀看您的電腦正在做什麼。

在預設的情況下,ps 指令只會顯示您所擁有的的程序。 例如:

% ps
  PID  TT  STAT      TIME COMMAND
  298  p0  Ss     0:01.10 tcsh
 7078  p0  S      2:40.88 xemacs mdoc.xsl (xemacs-21.1.14)
37393  p0  I      0:03.11 xemacs freebsd.dsl (xemacs-21.1.14)
48630  p0  S      2:50.89 /usr/local/lib/netscape-linux/navigator-linux-4.77.bi
48730  p0  IW     0:00.00 (dns helper) (navigator-linux-)
72210  p0  R+     0:00.00 ps
  390  p1  Is     0:01.14 tcsh
 7059  p2  Is+    1:36.18 /usr/local/bin/mutt -y
 6688  p3  IWs    0:00.00 tcsh
10735  p4  IWs    0:00.00 tcsh
20256  p5  IWs    0:00.00 tcsh
  262  v0  IWs    0:00.00 -tcsh (tcsh)
  270  v0  IW+    0:00.00 /bin/sh /usr/X11R6/bin/startx -- -bpp 16
  280  v0  IW+    0:00.00 xinit /home/nik/.xinitrc -- -bpp 16
  284  v0  IW     0:00.00 /bin/sh /home/nik/.xinitrc
  285  v0  S      0:38.45 /usr/X11R6/bin/sawfish

在這個範例裡可以看到 ps(1) 的輸出分成好幾個欄位。 PID 就是前面有提到的 process ID。 PID 的分配是從 1 開始一直到 99999,如果用完的話又會繞回來重頭開始分配 (若該 PID 已經在用了,則 PID 不會重新分配)。 TT 欄位是指這個程式在哪個 tty 上執行,在這裡可以先忽略不管。STAT 是程式的狀態,也可以先不要管。TIME 是這個程式在 CPU 上執行的時間——這通常不是程式總共花的時間, 因為當您開始執行程式後,大部份的程式在 CPU 上執行前會先花上不少時間等待 。 最後,COMMAND 是執行這個程式的命令列。

ps(1) 有幾個不同的選項組合可以用來變更顯示出來的資訊,其中一個最有用的組合是 auxwwa 可以顯示所有正在跑的程序的指令,不只是您自已的。 u 則是顯示程序的擁有者名稱以及記憶體使用情況。 x 可以把 daemon 程序顯示出來, 而 ww 可讓 ps(1) 顯示出每個程序完整的內容, 而不致因過長而被螢幕截掉了。

top(1) 也有類似的輸出。 一般的情況看像是這樣:

% top
last pid: 72257;  load averages:  0.13,  0.09,  0.03    up 0+13:38:33  22:39:10
47 processes:  1 running, 46 sleeping
CPU states: 12.6% user,  0.0% nice,  7.8% system,  0.0% interrupt, 79.7% idle
Mem: 36M Active, 5256K Inact, 13M Wired, 6312K Cache, 15M Buf, 408K Free
Swap: 256M Total, 38M Used, 217M Free, 15% Inuse

  PID USERNAME PRI NICE  SIZE    RES STATE    TIME   WCPU    CPU COMMAND
72257 nik       28   0  1960K  1044K RUN      0:00 14.86%  1.42% top
 7078 nik        2   0 15280K 10960K select   2:54  0.88%  0.88% xemacs-21.1.14
  281 nik        2   0 18636K  7112K select   5:36  0.73%  0.73% XF86_SVGA
  296 nik        2   0  3240K  1644K select   0:12  0.05%  0.05% xterm
48630 nik        2   0 29816K  9148K select   3:18  0.00%  0.00% navigator-linu
  175 root       2   0   924K   252K select   1:41  0.00%  0.00% syslogd
 7059 nik        2   0  7260K  4644K poll     1:38  0.00%  0.00% mutt
...

輸出的資訊分成兩個部份。開頭 (前五行) 秀出最近一個程序的 PID、系統平均負載 (系統有多忙錄的測試)、系統的開機時間 (從上次重開算起) 以及現在的時間等。 在開頭裡面的其他數字分別是在講有多少程序正在執行 (在本例中為47)、有多少記憶體及 swap space 被占用了,還有就是系統分別花了多少時間在不同的 CPU 狀態上。

接下來的部份是由好幾個欄位所構成,和 ps(1) 輸出的資訊類似。 就如同前例,您可以看到 PID、使用者名稱、CPU 花費的時間以及正在執行的指令。 top(1) 在預設的情況下還會告訴您程序用掉了多少的記憶體空間。 在這邊會分成兩欄,一個是總用量 (total size),另一個是實際用量 (resident size)——總用量是指這個應用程式需要的記憶體空間, 而實際用量則是指實際上該程式的記憶體使用量。 在這個例子裡面您可以看到 Netscape® 要了幾乎到 30 MB 的 RAM,但是只有用到 9 MB。

top(1) 每隔 2 秒鐘會自動更新顯示內容,可用 s 選項來改變間隔的時間。

3.9. Daemon、信號及終止程序

當在執行文書編輯器時,您可以很容易地使用它,叫它讀取檔案或是什麼的。 可以這樣做是因為編輯器有提供這些功能, 還有就是編輯器依附在一個終端機 (Terminal) 之上。 有些程式並不是設計成一直在接收使用者的輸入的, 所以它們在一開始執行的時候就從終端機斷開了。 例如說, 網頁伺服器整天都在回應網頁方面的要求,它通常不需要您輸入任何東西。 另外,像是把信從一個站傳送到另一個站的程式,也是這種類型的應用程式。

我們把這種程式稱作 daemon。 Daemon (惡魔、守護神) 是希臘神話中的角色:祂們不屬於善良陣營或邪惡陣營,是守護的小精靈。 大致上來說祂們就是在替人類做一些有用的事情, 跟今天的網頁伺服器或是郵件伺服器很像。 這也就是為何 BSD 的吉祥物,長期以來都是一隻穿著帆布鞋拿著三叉耙的快樂小惡魔的原因。

通常來說 deamon 程式的名字後面都會加一個字母 dBIND 是 Berkeley Internet Name Domain 的縮寫 (但實際上執行的程式名稱是 named)、Apache 網頁伺服器的程式名稱是 httpd、印表機服務程式是 lpd,依此類推。 這是習慣用法,並沒有硬性規定,例如 Sendmail 主要的寄信 daemon 是叫做 sendmail 而不是 maild,跟您想像的不一樣。

有些時候會需要跟某個 daemon 程序溝通, 這些溝通是透過所謂的信號(signal)來傳遞給該 daemon 程序(或是其他執行中的程序)。 藉由送出信號,您可以和一個 daemon (或是任何一個正在跑的程序) 溝通。 信號有很多種——有些有特定的意義,有些則是會由應用程式來解讀。 應用程式的說明文件會告訴您該程式是如何解讀信號的。 您只能送信號給您擁有的程序,送 kill(1)kill(2) 的信號給別人的程序是不被允許的。 不過 root 不受此限制,他可以送信號給任何人的程序。

FreeBSD 本身在某些情況也會送信號給應用程式。 假設有個應用程式寫得很爛,然後企圖要存取它不該碰的記憶體的時候,FreeBSD 會送一個 Segmentation Violation 信號 (SIGSEGV) 給這個程序。 又如果有一個應用程式用了 alarm(3) 的 system call 要求系統在過一段時間之後叫他一下,時間到了的時候鬧鐘的信號 (SIGALRM) 就會被送出了,其他的依此類推。

SIGTERM and SIGKILL 這兩個信號可以拿來終止程序。 用 SIGTERM 結束程序是比較有禮貌的方式,該程序會捕捉 (catch) 這個信號而了解到您想要把他關掉。 接著下來它會把它自已開的記錄檔通通關掉, 然後在關掉程序之前結束掉手邊的工作。 在某些情況下程序有可能會裝作沒看見 SIGTERM,假如它正在做一些不能中斷的工作的話。

SIGKILL 就沒有辦法被程序忽略了。 這是一個我管你正在幹嘛,現在就給我停下來的信號。 如果您送了 SIGKILL 信號給某個程序,FreeBSD 將會把它停掉[4]

這些是其他您有可能會要用到的信號: SIGHUPSIGUSR1,以及 SIGUSR2。 這些是通用的信號,當送出時不同的應用程式會有不同的反應。

假設您更動了您的網頁伺服器的設定檔—— 您想要叫網頁伺服器去重新讀取設定值。 您可以關閉後再重新啟動 httpd,但是這麼做會造成網頁伺服器暫停服務一段時間, 這樣子可能不太好。 大部份的 daemon 都寫成會去回應 SIGHUP。 當收到這個信號之後,它們會去重新讀取自已的設定檔。 因此您可以用送 SIGHUP 信號來取代關掉重開。 又因為沒有標準在規範如何回應這些信號,不同的 daemon 可能會有不同的行為,所以有疑問的話請先確認並翻閱 deamon 的說明文件。

信號是由 kill(1) 指令送出的,如範例所示:

過程 3.1. 送信號給程序

這個範例將會示範如何送一個信號給 inetd(8)inetd 的設定檔是 /etc/inetd.conf,而 inetd 會在收到 SIGHUP 的時候重新讀取這個設定檔。

  1. 找出您想要送信號的那個程序的 ID。 您會用到 ps(1) 以及 grep(1) 這兩個指令。 grep(1) 是用來在輸出中搜尋, 找出您指定的字串。 這個指令是由一般使用者執行,而 inetd(8) 是由 root 執行,所以在使用 ps(1) 時需要加上 ax 選項。

    % ps -ax | grep inetd
      198  ??  IWs    0:00.00 inetd -wW

    因此可知 inetd(8) 的 PID 為 198。 在某些情況下 grep inetd 這個指令本身也會出現在輸出裡。 這是因為 ps(1) 乃是找所有執行中的程序的方式造成的。

  2. kill(1) 來送信號。 又因為 inetd(8) 是由 root 執行的,您必須用 su(1) 切換成 root先。

    % su
    Password:
    # /bin/kill -s HUP 198

    一般情況對大多數 UNIX® 指令來講,當 kill(1) 執行成功時並不會輸出任何訊息。 假設您送一個信號給某個不是您所擁有的程序, 那麼您就會吃到這個錯誤訊息: kill: PID: Operation not permitted。 而如果您打錯 PID 的話,那就會把信號送給錯誤的程序。 這樣可能會很糟, 不過如果您夠幸運的話,可能剛好就只是把信號送給一個非使用中的 PID,那您就只會看到 kill: PID: No such process 而已。

    為什麼用 /bin/kill?:

    很多 shell 有提供內建的 kill 指令。 也就是說這種 shell 會直接送信號,而不是執行 /bin/kill。 這樣是蠻方便的沒錯啦,但是不同的 shell 會有不同的語法來指定信號的名稱等。 與其嘗試去把它們通通學會,不如就單純的直接用 /bin/kill ... 吧。

要送其他的信號的話也是非常類似,就視需要把指令中的 TERMKILL 替換掉即可。

重要:

隨便抓一個系統中的程序然後把他砍掉並不是個好主意。 特別是 init(8), process ID 1,一個非常特別的程序。 執行 /bin/kill -s KILL 1 的結果就是系統立刻關機。 因此在您按下 Return 要執行 kill(1)之前, 請一定要記得再次確認您下的參數。

3.10. Shells

在 FreeBSD 中,很多日常的工作是在一個叫做 shell 的文字介面中完成的。 Shell 的主要工作就是從輸入中收到命令並執行它們。 許多 shell 也有內建一些有助於日常工作的指令, 像是檔案管理、檔案比對、命令列編輯、指令巨集以及環境變數等。 FreeBSD 有內附了幾個 shell,像是 sh, Bourne Shell,以及 tcsh,改良版的 C-shell。 還有許多其他的 shell 可以從 FreeBSD Ports Collection 中取得,像是 zsh 以及 bash 等。

您用哪個 shell 呢? 其實每個人的喜好都不一樣。 如果您是一個 C 程式設計師,那對於使用像是 tcsh 這種 C-like 的 shell 可能會感到相當愉快。 如果你是從 Linux 跳過來的,或者您是一個 UNIX® 新手,那您也許會想要用 bash 來當作文字介面。 每一個 shell 都有自已獨特之處,至於這些特點能不能配合您的工作環境? 那就是您選擇 shell 的重點了。

檔名自動補齊就是常見的 shell 功能。 首先輸入指令或檔案的前幾個字母,這時通常您只需要按下 Tab 鍵,接下來 shell 就會自動把指令或是檔案名稱剩餘的部份補齊。 假設您有兩個檔案分別叫作 foobarfoo.bar。 現在要刪掉 foo.bar,那麼可以輸入: rm fo[Tab].[Tab]

Shell 會印出這個: rm foo[嗶].bar

[嗶] 是 console 的響鈴,這嗶的一聲是 shell 在告訴我說它沒有辦法完全自動補齊檔名,因為有不只一個檔名符合條件。 foobarfoo.bar 都是 fo 開頭的檔名,不過它至少可以補齊到 foo。 如果您接著輸入 . 然後再按 Tab 一次,那 shell 就能夠替您把剩下的檔名填滿了。

Shell 的另一項特點是使用了環境變數。 環境變數是以變數與鍵值(variable/key)的對應關係儲存於 shell 的環境空間中,任何由 shell 所產生的程序都可以讀取此空間, 因此這個空間儲存了許多程序的設定組態。 在此附上 一份常見環境變數與其涵義的列表:

變數詳細說明
USER目前登入的使用者名稱。
PATH以冒號(:)隔開的目錄列表,用以搜尋執行檔的路徑。
DISPLAY若存在這個環境變數,則代表 X11 連結顯示器的網路名稱。
SHELL目前使用的 shell。
TERM使用者終端機的名稱,能藉由此變數判斷終端機的能力。
TERMCAPDatabase entry of the terminal escape codes to perform various terminal functions.
OSTYPE作業系統的種類,如:FreeBSD。
MACHTYPE目前系統所用的 CPU 架構。
EDITOR使用者偏好的文字編輯器。
PAGER使用者偏好的文字分頁器(text pager)。
MANPATH以冒號(:)隔開的目錄列表,用以搜尋 manual pages 的路徑。

在不同的 shell 底下設定環境變數的方式也有所不同。 舉例來說,在 C-Style 的 shell 底下,像是 tcshcsh,你必須使用 setenv 來設定環境變數。 但在 Bourne shells 底下,像是 shbash,你則必須使用 export 來設定你所使用的環境變數。 再舉個例子來說,若要設定或是修改 EDITOR 這個環境變數,在 cshtcsh 下設定 EDITOR 這個環境變數為 /usr/local/bin/emacs 的指令是:

% setenv EDITOR /usr/local/bin/emacs

在 Bourne shells 下則是:

% export EDITOR="/usr/local/bin/emacs"

大多數的 shell 都支援使用者在命令列中將 $ 字元放在變數之前,以取得環境變數的值。 舉例來說,echo $TERM 會 顯示出 $TERM 的設定值,這是因為 shell 取得了 $TERM 的設定值, 並將其傳給 echo 顯示出來。

Shell 中有某些特別的字元是來表示特殊的資料,我們將其稱作 meta-characters。 其中最常見的是 * 字元,他代表了檔名中的任意字元。 這些特殊字元可以用在檔名展開(filename globbing)上,舉例來說,輸入 echo * 會和輸入 ls 得到幾乎相同的結果,這是因為 shell 會將所有符合 * 字元的檔案傳到命令列上,再由 echo 顯示出來。

為了避免 shell 轉譯這些特殊字元,我們可以在這些特殊字元前放一個反斜線 (\) 字元使他們跳脫(escape) shell 的轉譯。舉例來說, echo $TERM 會印出你目前設定的終端機格式, echo \$TERM 則會直接印出 $TERM 這幾個字。

3.10.1. 變更你的 Shell

變更 shell 最簡單的方法就是透過 chsh 命令。 執行 chsh 將會呼叫環境變數中 EDITOR 指定的文字編輯器。 如果沒有設定,則預設是 vi。 請依照需求去修改 Shell: 的值。

你也可以透過 chsh 的參數 -s, 這可以直接設定你的 shell 而不需要透過任何文字編輯器。 例如, 假設想把所用的 shell 改為 bash, 可以透過下列的方式:

% chsh -s /usr/local/bin/bash

注意:

你所使用的 shell 必須 列於 /etc/shells 裡頭。 如果是由 Ports Collection 來裝 shell, 那這個步驟已經完成了。 但若是手動安裝了一個 shell, 那麼就必須為新安裝的 shell 進行設定。

舉例來說,若手動安裝了 bash 並將它置於 /usr/local/bin 底下,你還得:

# echo "/usr/local/bin/bash" >> /etc/shells

然後再重新執行 chsh

3.11. 文字編輯器

在 FreeBSD 中有許多設定必須透過編輯文字檔完成。 因此,若能熟悉文字編輯器是再好不過的。 FreeBSD 本身(指 base system)就附有幾種文字編輯器, 此外,你也可以透過 Ports Collection 來安裝其他的文字編輯器。

最簡單易學的文字編輯器叫做 ee, 代表了其全名 easy editor。 要開始使用 ee, 必須在命令列上輸入 ee filename, 這邊的 filename 代表你想要編輯的檔案名稱。 舉例來說,要編輯 /etc/rc.conf,就要輸入 ee /etc/rc.conf。 而在 ee 的操作介面下, 所有編輯器的功能與操作都會顯示在螢幕的正上方。 其中的插入符號(^)代表鍵盤上的 Ctrl 鍵,所以 ^e 就等同於 Ctrl+e 。 若要結束 ee,請按下 Esc 鍵,接著選擇 leave editor 即可。 此時如果該檔案有修改過,編輯器會提醒你是否要存檔。

此外,FreeBSD 也內附了幾個好用的文字編輯器,像是 base system 的 vi 及 FreeBSD Ports Collection 內的其他編輯器, 比如 Emacsvim (editors/emacseditors/vim)。 這些文字編輯器提供更強的功能,但是也比較難學習。 然而若要從事大量文字編輯工作, 那麼花點時間來學習這些好用的編輯器, 會在日後為您省下更多的時間。

3.12. 設備及設備節點

設備(device)主要是指跟硬體比較有關的術語, 包括磁碟、印表機、顯示卡和鍵盤。 FreeBSD 開機過程當中, 大多數硬體通常都能偵測到並顯示出來,也可以查閱 /var/run/dmesg.boot 內有開機的相關訊息。

舉例來說,acd0即為第一台 IDE 光碟機的代號, 而 kbd0 則代表鍵盤。

UNIX® 作業系統, 大部分的設備都是透過叫做 device nodes(設備節點)的特殊檔案來作存取, 而這些檔案都位於 /dev 目錄。

3.12.1. 建立設備節點

若要在系統上建立新節點,或者是要編譯某些新硬體的支援軟體, 那麼就要先新增設備節點。

3.12.1.1. DEVFS (DEVice File System)

設備檔案系統(或稱為 DEVFS) 是指在整體檔案系統 namespace 提供 kernel 的設備 namespace。 DEVFS 乃是維護這些檔案系統,而不能新增或修改這些設備節點。

細節請參閱 devfs(5) 說明。

3.13. 更多資訊

3.13.1. Manual 線上說明

在使用 FreeBSD 時,最詳細的使用說明莫過於 man 線上說明。 幾乎各程式都會有附上簡短說明,以介紹該程式的基本功能跟相關參數用法。 可以透過 man 指令來閱讀這些說明,而 man 指令的使用相當簡單易懂:

% man command

command 處就是想要知道的指令。 舉個例子, 若要知道 ls 的詳細用法,就可以打:

% man ls

而各線上說明因為性質不同,而區分為下列的數字章節:

  1. 使用者指令。

  2. 系統呼叫(System call) 及錯誤代號。

  3. C 語言函式庫。

  4. 各設備的驅動程式。

  5. 檔案格式。

  6. 小遊戲程式及其他娛樂程式。

  7. 雜項工具、其他資訊。

  8. 系統維護、操作的指令。

  9. Kernel 開發用途。

有些情況會有同樣主題但不同章節。 舉個例子,系統內會有 chmod 指令,但也有 chmod() 系統呼叫。 在這種情況,man 應該要指定所要查詢的章節:

% man 1 chmod

如此一來就會查 chmod 指令部分。 通常在寫文件時會把有參考到某特定章節的 man 號碼也一併寫在括號內。 所以 chmod(1) 就是指 chmod 指令,而 chmod(2) 則是指系統呼叫的部分。

如果您已經知道命令的名稱,只是不知道要怎樣使用的話,那就比較好辦。 但若不知道要用哪個指令時,該怎麼辦呢? 這個時候,就可以利用 man 的搜尋關鍵字功能, 以在各說明的介紹部分搜尋相關字眼。,它的選項是 -k

% man -k mail

如此一來會看到一堆有 mail 關鍵字的說明, 事實上該功能與 apropos 指令是一樣的。

而有時你會看到像是 /usr/bin 有許多看起來頗炫的指令,但不知其用途? 只要簡單輸入:

% cd /usr/bin
% man -f *

或者是

% cd /usr/bin
% whatis *

這兩者的指令效果是一樣的。

3.13.2. GNU Info 檔案

FreeBSD 有許多程式跟工具來自於自由軟體基金會(FSF)。 除了 man 線上說明之外,這些程式提供了另外一種更具有彈性的 hypertext 格式文件, 叫做 info。 可以用 info 指令來閱讀,或者若有裝 emacs 亦可透過 emacs 的 info 模式閱讀。

要用 info(1) 指令,只需打:

% info

h 會有簡單說明,而若要快速查閱相關操作方式, 則請按 ?



[1] 這就是 i386 的意義。 注意即使您不是在 Intel 的 386 處理器上執行 FreeBSD ,一樣是i386。 這不是指你的處理器的型號,這裡顯示的是你處理器的架構

[2] 這些啟動的 script 是在開機的時候 FreeBSD 會自動執行的程式。 他們主要的功能是將所有該執行的東西設定好, 並將您設定成背景執行的服務啟動。

[3] syscons(4)atkbd(4)vidcontrol(1)、以及 kbdcontrol(1)等 manual page 中,對於 FreeBSD 的 console 及鍵盤驅動程式有詳細的技術說明。 我們在這裡不討論細節, 有興趣的讀者隨時可以在 manual pages 中查到關於運作方式的更詳細且完整的解釋。

[4] 不完全正確——還是有少數東西不能被中斷。 例如有個程序正在從網路上的別的電腦讀一個檔案, 而那部電腦因為某些理由連不到 (機器被關掉,或是網路爛掉了), 那這個程序我們就說他是一個不能中斷的程序。 通常在經過兩分鐘左右之後這個程序會逾時。 當發生逾時的時候這個程序就會被結束掉了。

章 4. 軟體套件管理篇:Packages 及 Ports 機制

4.1. 概述

儘管 FreeBSD 在 base system 已加了很多系統工具。 然而,在實務運用上,您可能仍需要安裝額外的軟體。 FreeBSD 提供了 2 種安裝應用程式的套件管理系統︰Ports Collection (以 soucre 來編譯、安裝) 和 package(預先編譯好的 binary 檔)。 上述的方式,無論要用哪一種,都可以由像是 CDROM 等或網路上來安裝想裝的最新版軟體。

讀完這章,您將了解:

  • 如何以 packages 來安裝軟體。

  • 如何以 ports 來安裝軟體。

  • 已安裝的 packages 或 ports 要如何移除。

  • 如何更改(override) ports collection 所使用的預設值。

  • 如何在套件管理系統中,找出想裝的軟體。

  • 如何升級已安裝的軟體。

4.2. 安裝軟體的各種方式介紹

通常要在 UNIX® 系統上安裝軟體時,有幾個步驟要作:

  1. 先下載該軟體壓縮檔(tarball),有可能是原始碼或是 binary 執行檔。

  2. 解開該壓縮檔。(通常是以 compress(1) , gzip(1)bzip2(1) 壓縮的)

  3. 閱讀相關文件檔,以了解如何安裝。(通常檔名是 INSTALLREADME ,或在 doc/ 目錄下的一些文件)

  4. 如果所下載的是原始碼,可能要先修改 Makefile 或是執行 ./configure 之類的 script ,接著再編譯該軟體。

  5. 最後測試再測試與安裝。

如果一切順利的話,就這麼簡單。 如果在安裝非專門設計(移植)給 FreeBSD 的軟體時出問題, 那可能需要修改一下它的程式碼,才能正常使用。

當然,我們可以在 FreeBSD 上使用上述的傳統方式來安裝軟體, 但是,我們還有更簡單的選擇。 FreeBSD 提供了兩種省事的軟體管理機制: packages 和 ports。 就在寫這篇文章的時候, 已經有超過 24,000 個 port 軟體可以使用。

所謂的 FreeBSD package 就是別人把該應用程式編譯、打包完畢。 該 package 會包括該應用程式的所有執行檔、設定檔、文件等。 而下載到硬碟上的 package 都可透過 FreeBSD 套件管理指令來進行管理,比如: pkg_add(1)pkg_delete(1)pkg_info(1) 等指令。 所以,只需簡單打個指令就可輕鬆安裝新的應用程式了。

而 FreeBSD port 則是用一些檔案,來自動處理應用程式的安裝流程。

請記住:如果打算自己來編譯的話,需要執行很多操作步驟 (下載、解壓、patch、編譯、安裝)。 而 port 呢,則是涵蓋所有需要完成這些工作的必備步驟, 所以只需打一些簡單的指令,那些原始程式碼就會自動下載、解壓、 patch、編譯,直至安裝完畢。

事實上,ports 機制還可以用來產生 packages,以便他人可以用 pkg_add 來安裝, 或是稍後會介紹到的其他套件管理指令。

而 packages 以及 ports 它們都是一樣會認 dependencies(軟體相依關係)。 假設:您想安裝某程式,但它有相依另一個已裝的函式庫(library), 而在 FreeBSD 的 port 以及 package 都有這程式以及該函式庫了。 所以無論是用 pkg_add 指令或者 port 方式來裝該程式, 這兩者(package、port)都會先檢查有沒有裝該函式庫, 若沒有就會自動先裝該函式庫了。

這兩種技術都很相似,您可能會好奇為什麼 FreeBSD 會弄出這兩種技術來呢。 其實,packages 和 ports 都有它們各自的長處, 使用哪一種完全取決於您自己的喜好。

Package 好處在於:
  • 同樣是壓縮過的 package 與原始碼 tarball 相比, 前者通常會比後者小多了。

  • package 並不需再進行編譯。 對大型應用程式如 MozillaKDEGNOME 而言,這點顯得相當重要, 尤其是使用速度緩慢的機器。

  • 不需要瞭解如何在 FreeBSD 上編譯軟體的相關細節過程, 即可使用 package。

Ports 好處在於:
  • 為了讓 package 能在大多數系統上順利執行, 通常在編譯時會使用比較保守的選項。 然而, 透過 port 安裝的話,則可針對特定環境(比如: Pentium 4 或 Athlon CPU) 來調整選項,以符合需求。

  • 有些程式在編譯時,會有一些選項可以選擇。 舉例來說,Apache 可以設定一大堆的編譯選項。 若透過 port 來安裝的話, 會比較彈性多了,可以自己選而不必使用預設的編譯選項。

    在某些情況,同樣的程式但不同編譯選項,則會分成不同的 package。 比如: Ghostscript 會因為是否要裝 X11 server, 而劃分為 ghostscript 以及 ghostscript-nox11 這兩種 package。 如此的調整對 package 算是可成立的, 但若該程式有一個以上或兩種不同的編譯選項時, 這對 package 就沒辦法了。

  • 某些軟體的禁止以 binary 方式散佈, 或者說必須以原始碼方式散佈才可。

  • 有些人並不信任 binary 套件機制,因為他們覺得至少有原始碼, (理論上)就可以自己檢閱,並尋找是否有潛在的問題。

  • 若要對軟體加上自己改過的 patch, 那麼就必須要先有原始碼才能去上相關 patch 修正。

  • 有些人喜歡有原始碼在手邊, 所以他們無聊時就可以自己閱讀、鑽研、借用 (當然要符合原始碼本身的授權規定)原始碼等等。

若想注意 port 更新動態的話,可以訂閱 FreeBSD ports 郵遞論壇 以及 FreeBSD ports bugs 郵遞論壇

警告:

在安裝軟體前,最好先看 http://vuxml.freebsd.org/ 內是否有該軟體的安全漏洞通報。

此外,也可以裝 ports-mgmt/portaudit,它會自動檢查所有已裝的 的軟體是否有已知的安全漏洞,另外,它還會在裝軟體的編譯過程前先行檢查。 也可以在裝了某些軟體之後,用 portaudit -F -a 來作全面強制安檢。

本章接下來將介紹如何在 FreeBSD 使用 package 及 port 來安裝、管理 third-party 軟體。

4.3. 尋找想裝的軟體

在安裝任何軟體之前,你必須先了解你想要什麼的軟體, 以及該軟體叫做什麼名稱。

FreeBSD 上可裝的軟體清單不斷在增加中, 不過,我們很慶幸有幾種方式可以來找你想裝的軟體:

  • FreeBSD 網站上有更新頻繁的軟體清單,在 http://www.FreeBSD.org/ports/ 。 各 ports 皆依其性質而分門別類,既可以透過軟體名稱來搜尋 (如果知道名字的話), 也可以在分類中列出所有可用的軟體。

  • 由 Dan Langille 所維護 FreshPorts 網站,網址在 http://www.FreshPorts.org/。 FreshPorts 會不斷追蹤 port tree 中的各種變化, 也可以針對某些 port 以列入 追蹤名單(watch) 內, 當有任何軟體升級時,就會發 email 提醒。

  • 如果不知道想裝的軟體名稱,那麼可透過像是 FreshMeat (http://www.freshmeat.net/) 這類的網站來找, 如果找到了,可以回 FreeBSD 網站去看一下這個應用程式是否已經被 port 進去了。

  • 若知道該 port 的正確名稱,但不知道放在哪個分類目錄,可以用 whereis(1) 指令來找出來。 只要打 whereis file 即可,而 file 的地方請改為想裝的軟體名稱。 若找到該軟體,就會告訴你,就像下面這樣:

    # whereis lsof
    lsof: /usr/ports/sysutils/lsof

    如此一來,就會知道 lsof (系統工具程式) 是放在 /usr/ports/sysutils/lsof 目錄。

  • 此外,也可以用 echo(1) 輕鬆找出該 port 是位於 porte tree 的何處。 舉例來說:

    # echo /usr/ports/*/*lsof*
    /usr/ports/sysutils/lsof

    請注意,這也會顯示 /usr/ports/distfiles 目錄內有符合檔名的檔案。

  • 還有另一招,就是用 Ports Collection 本身內建的搜尋機制。 要用的時候,請先切換到 /usr/ports 目錄。 然後,打 make search name=程式名稱 ,其中 程式名稱 請改為想找的軟體名稱。 舉例來說,若要找的是 lsof 的話,那麼就是:

    # cd /usr/ports
    # make search name=lsof
    Port:   lsof-4.56.4
    Path:   /usr/ports/sysutils/lsof
    Info:   Lists information about open files (similar to fstat(1))
    Maint:  obrien@FreeBSD.org
    Index:  sysutils
    B-deps:
    R-deps: 

    這些搜尋結果中,要注意的是 Path: 這行, 因為這行會告訴你可以在哪邊找到該 port。 而搜尋結果的其他部分,因為與 port 安裝較無關係,所以這裡就不講了。

    若要更徹底的搜尋,那麼可以改用 make search key=string,其中 string 請改為想搜尋的關鍵字。 如此一來會找 port 名稱、軟體簡介(comments)、軟體敘述檔(descriptions) 以及軟體相依關係(dependencies)裡面是否有符合關鍵字, 此外,不清楚軟體名稱的話,也可以拿來找有符合關鍵字主題的 port。

    剛講的這兩種方式,搜尋字眼都是 case-insensitive(不必區分大小寫)。 比如,搜尋 LSOFlsof 兩者結果都會是一樣的。

4.4. Using pkg for Binary Package Management

pkg is the next generation replacement for the traditional FreeBSD package management tools, offering many features that make dealing with binary packages faster and easier.

pkg is not a replacement for port management tools like ports-mgmt/portmaster or ports-mgmt/portupgrade. These tools can be used to install third-party software from both binary packages and the Ports Collection, while pkg installs only binary packages.

4.4.1. Getting Started with pkg

FreeBSD 8.4 and later includes a bootstrap utility which can be used to download and install pkg, along with its manual pages.

To bootstrap the system, run:

# /usr/sbin/pkg

For earlier FreeBSD versions, pkg must instead be installed from the Ports Collection or as a binary package.

To install the port, run:

# cd /usr/ports/ports-mgmt/pkg
# make
# make install clean

When upgrading an existing system that originally used the older package system, the database must be converted to the new format, so that the new tools are aware of the already installed packages. Once pkg has been installed, the package database must be converted from the traditional format to the new format by running this command:

# pkg2ng

注意:

This step is not required for new installations that do not yet have any third-party software installed.

重要:

This step is not reversible. Once the package database has been converted to the pkg format, the traditional pkg_* tools should no longer be used.

注意:

The package database conversion may emit errors as the contents are converted to the new version. Generally, these errors can be safely ignored. However, a list of third-party software that was not successfully converted will be listed after pkg2ng has finished and these applications must be manually reinstalled.

To ensure that the FreeBSD Ports Collection registers new software with pkg, and not the traditional packages format, FreeBSD versions earlier than 10.X require this line in /etc/make.conf:

WITH_PKGNG=	yes

The pkg package management system uses a package repository for most operations. The default package repository location is defined in /usr/local/etc/pkg.conf or by the PACKAGESITE environment variable, which overrides the configuration file.

Additional pkg configuration options are described in pkg.conf(5).

Usage information for pkg is available in pkg(8) or by running pkg without additional arguments.

Each pkg command argument is documented in a command-specific manual page. To read the manual page for pkg install, for example, run either of these commands:

# pkg help install
# man pkg-install

The rest of this section demonstrates common binary package management tasks which can be performed using pkg. Each demonstrated command provides many switches to customize its use. Refer to a command's help or man page for details and more examples.

4.4.2. Obtaining Information About Installed Packages

Information about the packages installed on a system can be viewed by running pkg info which, when run without any switches, will list the package version for either all installed packages or the specified package.

For example, to see which version of pkg is installed, run:

# pkg info pkg
pkg-1.1.4_1

4.4.3. Installing and Removing Packages

To install a binary package use the following command, where packagename is the name of the package to install:

# pkg install packagename

This command uses repository data to determine which version of the software to install and if it has any uninstalled dependencies. For example, to install curl:

# pkg install curl
Updating repository catalogue
/usr/local/tmp/All/curl-7.31.0_1.txz          100% of 1181 kB 1380 kBps 00m01s

/usr/local/tmp/All/ca_root_nss-3.15.1_1.txz   100% of  288 kB 1700 kBps 00m00s

Updating repository catalogue
The following 2 packages will be installed:

        Installing ca_root_nss: 3.15.1_1
        Installing curl: 7.31.0_1

The installation will require 3 MB more space

0 B to be downloaded

Proceed with installing packages [y/N]: y
Checking integrity... done
[1/2] Installing ca_root_nss-3.15.5_1... done
[2/2] Installing curl-7.31.0_1... done
Cleaning up cache files...Done

The new package and any additional packages that were installed as dependencies can be seen in the installed packages list:

# pkg info
ca_root_nss-3.15.5_1	The root certificate bundle from the Mozilla Project
curl-7.31.0_1	Non-interactive tool to get files from FTP, GOPHER, HTTP(S) servers
pkg-1.1.4_6	New generation package manager

Packages that are no longer needed can be removed with pkg delete. For example:

# pkg delete curl
The following packages will be deleted:

	curl-7.31.0_1

The deletion will free 3 MB

Proceed with deleting packages [y/N]: y
[1/1] Deleting curl-7.31.0_1... done

4.4.4. Upgrading Installed Packages

Packages that are outdated can be found with pkg version. If a local ports tree does not exist, pkg-version(8) will use the remote repository catalogue. Otherwise, the local ports tree will be used to identify package versions.

Installed packages can be upgraded to their latest versions by typing pkg upgrade. This command will compare the installed versions with those available in the repository catalogue. When finished, it will list the applications that have newer versions. Type y to proceed with the upgrade or n to cancel the upgrade.

4.4.5. Auditing Installed Packages

Occasionally, software vulnerabilities may be discovered in third-party applications. To address this, pkg includes a built-in auditing mechanism. To determine if there are any known vulnerabilities for the software installed on the system, run:

# pkg audit -F

4.4.6. Automatically Removing Leaf Dependencies

Removing a package may leave behind dependencies which are no longer required. Unneeded packages that were installed as dependencies can be automatically detected and removed using:

# pkg autoremove
Packages to be autoremoved:
	ca_root_nss-3.13.5

The autoremoval will free 723 kB

Proceed with autoremoval of packages [y/N]: y
Deinstalling ca_root_nss-3.15.1_1... done

4.4.7. Backing Up the Package Database

Unlike the traditional package management system, pkg includes its own package database backup mechanism. To manually back up the contents of the package database, run the following command, replacing pkgng.db with a suitable file name:

# pkg backup -d pkgng.db

Additionally, pkg includes a periodic(8) script to automatically perform a daily back up of the package database. This functionality is enabled if daily_backup_pkgdb_enable is set to YES in periodic.conf(5).

提示:

To disable the periodic script from backing up the package database, set daily_backup_pkgdb_enable to NO in periodic.conf(5).

To restore the contents of a previous package database backup, run:

# pkg backup -r /path/to/pkgng.db

4.4.8. Removing Stale Packages

By default, pkg stores binary packages in a cache directory defined by PKG_CACHEDIR in pkg.conf(5). When upgrading packages with pkg upgrade, old versions of the upgraded packages are not automatically removed.

To remove these outdated binary packages, run:

# pkg clean

4.4.9. Modifying Package Metadata

Software within the FreeBSD Ports Collection can undergo major version number changes. To address this, pkg has a built-in command to update package origins. This can be useful, for example, if lang/php5 is renamed to lang/php53 so that lang/php5 can now represent version 5.4.

To change the package origin for the above example, run:

# pkg set -o lang/php5:lang/php53

As another example, to update lang/ruby18 to lang/ruby19, run:

# pkg set -o lang/ruby18:lang/ruby19

As a final example, to change the origin of the libglut shared libraries from graphics/libglut to graphics/freeglut, run:

# pkg set -o graphics/libglut:graphics/freeglut

注意:

When changing package origins, it is important to reinstall packages that are dependent on the package with the modified origin. To force a reinstallation of dependent packages, run:

# pkg install -Rf graphics/freeglut

4.5. 使用 Ports 管理機制

The Ports Collection is a set of Makefiles, patches, and description files stored in /usr/ports. This set of files is used to compile and install applications on FreeBSD. Before an application can be compiled using a port, the Ports Collection must first be installed. If it was not installed during the installation of FreeBSD, use one of the following methods to install it:

過程 4.1. Portsnap 方式

The base system of FreeBSD includes Portsnap. This is a fast and user-friendly tool for retrieving the Ports Collection and is the recommended choice for most users. This utility connects to a FreeBSD site, verifies the secure key, and downloads a new copy of the Ports Collection. The key is used to verify the integrity of all downloaded files.

  1. To download a compressed snapshot of the Ports Collection into /var/db/portsnap:

    # portsnap fetch
  2. 若是第一次跑 Portsnap 的話, 則需要先解壓到 /usr/ports

    # portsnap extract
  3. After the first use of Portsnap has been completed as shown above, /usr/ports can be updated as needed by running:

    # portsnap fetch
    # portsnap update

    When using fetch, the extract or the update operation may be run consecutively, like so:

    # portsnap fetch update
過程 4.2. Subversion Method

If more control over the ports tree is needed or if local changes need to be maintained, Subversion can be used to obtain the Ports Collection. Refer to the Subversion Primer for a detailed description of Subversion.

  1. Subversion must be installed before it can be used to check out the ports tree. If a copy of the ports tree is already present, install Subversion like this:

    # cd /usr/ports/devel/subversion
    # make install clean

    If the ports tree is not available, or pkg is being used to manage packages, Subversion can be installed as a package:

    # pkg install subversion
  2. Check out a copy of the ports tree. For better performance, replace svn0.us-east.FreeBSD.org with a Subversion mirror close to your geographic location:

    # svn checkout https://svn0.us-east.FreeBSD.org/ports/head /usr/ports
  3. As needed, update /usr/ports after the initial Subversion checkout:

    # svn update /usr/ports

The Ports Collection installs a series of directories representing software categories with each category having a subdirectory for each application. Each subdirectory, also referred to as a ports skeleton, contains a set of files that tell FreeBSD how to compile and install that program. Each port skeleton includes these files and directories:

  • Makefile: contains statements that specify how the application should be compiled and where its components should be installed.

  • distinfo: contains the names and checksums of the files that must be downloaded to build the port.

  • files/: this directory contains any patches needed for the program to compile and install on FreeBSD. This directory may also contain other files used to build the port.

  • pkg-descr: provides a more detailed description of the program.

  • pkg-plist: a list of all the files that will be installed by the port. It also tells the ports system which files to remove upon deinstallation.

Some ports include pkg-message or other files to handle special situations. For more details on these files, and on ports in general, refer to the FreeBSD Porter's Handbook.

The port does not include the actual source code, also known as a distfile. The extract portion of building a port will automatically save the downloaded source to /usr/ports/distfiles.

4.5.1. Ports 的安裝方式

下面我們會介紹如何使用 Ports Collection 來安裝、移除軟體的基本用法。 至於其他可用的 make 詳細用法與環境設定,可參閱 ports(7)

警告:

Before compiling any port, be sure to update the Ports Collection as described in the previous section. Since the installation of any third-party software can introduce security vulnerabilities, it is recommended to first check http://vuxml.freebsd.org/ for known security issues related to the port. Alternately, if ports-mgmt/portaudit is installed, run portaudit -F before installing a new port. This command can be configured to automatically perform a security audit and an update of the vulnerability database during the daily security system check. For more information, refer to the manual page for portaudit and periodic(8).

提到 Ports Collection,首先要先說明的是:何謂 skeleton。 簡單來講,port skeleton 就是讓軟體如何在 FreeBSD 順利編譯、安裝的最基本檔案組合。 每份 port skeleton 基本上會有:

  • Makefile 檔。 這個 Makefile 內容有分許多部分, 是用來指定要如何編譯,以及該裝在系統的何處。

  • distinfo 檔。 編譯該軟體所需下載的檔案、checksum(使用 md5(1)sha256(1) 來檢驗檔案)都會記錄在這檔, 以確保所下載的檔案是正確無誤的。

  • files 目錄。 這目錄放的是讓軟體正常編譯、 安裝的 patch 檔。 Patches 檔基本上是一些小檔案,並針對特定檔案來做修改, 而且是純文字檔格式, 基本上內容通常會像是 Remove line 10(刪除第 10 行)Change line 26 to this ...(把第 26 行改為...) 之類的。 這些 Patches 通常也稱為 diffs ,因為都是由 diff(1) 程式所產生的。

    此外,本目錄也可能會放一些協助編譯該 port 的檔案。

  • pkg-descr 檔,內容是比較詳細的軟體介紹, 通常會寫得比較多行。

  • pkg-plist 檔,該 port 會安裝的所有檔案清單。 也是告訴系統在移除該 port 時,需要刪除哪些檔案。

有些 port 還會有其他檔案,像是 pkg-message 檔。 port 系統在一些情況時,會用這些檔案。 如果想知道這些檔案的更多細節用途,以及 port 一般用法,請參閱 FreeBSD Porter's Handbook

port 內寫的是告訴系統如何編譯 source code 的相關指令, 但並不是真正的 source code。 而 source code 可以從光碟或網路(Internet)來取得, 該軟體開發者可能會把 source code 以各種格式來發佈。 通常是以 tar 以及 gzip 這兩者工具一起壓縮的檔案, 也有可能是以其他工具壓縮,或根本沒壓縮。 而軟體的 source code 無論是以哪一種壓縮檔型態,我們都稱之為 distfile。 下面將介紹兩種安裝 FreeBSD port 的方式。

注意:

要安裝 port 的話,請務必切為 root 身份。

警告:

在安裝任何 port 之前,請務必確認有更新 Ports Collection 到最新版, 此外請檢閱 http://vuxml.freebsd.org/ 來檢查所要裝的 port 是否有相關安全漏洞議題需要注意的。

portaudit 會在安裝任何 port 之前, 先自動檢查是否有相關已知的安全漏洞。這個工具在 Ports Collection 內有 (ports-mgmt/portaudit)。 在安裝 port 之前,可以先跑 portaudit -F 指令, 如此一來就會抓最新的資安漏洞資料庫回來核對。 每天的系統定期安檢會自動更新資料庫,並作安全稽核。 詳情請參閱 portaudit(1) 以及 periodic(8) 的線上說明。

Ports Collection 會假設你的網路是可正常連線的。 如果沒有的話,那麼需手動把所需的 distfile 檔複製到 /usr/ports/distfiles 才行。

開始操作之前,要先進入打算安裝的 port 目錄內:

# cd /usr/ports/sysutils/lsof

一旦進入 lsof 目錄後,就可以看到這個 port 的 skeleton 結構。 接下來,就是編譯,也就是 build 這個 port。 只需簡單輸入 make 指令,就可輕鬆完成編譯。 完成後,應該可以看到類似下面訊息:

# make
>> lsof_4.57D.freebsd.tar.gz doesn't seem to exist in /usr/ports/distfiles/.
>> Attempting to fetch from ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/.
===>  Extracting for lsof-4.57
...
[extraction output snipped]
...
>> Checksum OK for lsof_4.57D.freebsd.tar.gz.
===>  Patching for lsof-4.57
===>  Applying FreeBSD patches for lsof-4.57
===>  Configuring for lsof-4.57
...
[configure output snipped]
...
===>  Building for lsof-4.57
...
[compilation output snipped]
...
#

請注意:編譯完成後,就會回到提示列(prompt)。接下來就是安裝該 port 了,要裝的話,只需在原本的 make 指令後面再加上一個字即可, 那個字就是 install

# make install
===>  Installing for lsof-4.57
...
[installation output snipped]
...
===>   Generating temporary packing list
===>   Compressing manual pages for lsof-4.57
===>   Registering installation for lsof-4.57
===>  SECURITY NOTE:
      This port has installed the following binaries which execute with
      increased privileges.
#

一旦回到提示列(prompt),就可以執行剛裝的程式了。 另外,因為 lsof 這程式執行時會有額外權限, 所以會出現安全警告。在編譯、安裝 port 的時候, 請留意任何出現的警告。

此外,建議刪除編譯用的工作目錄(預設是 work), 這目錄內為在編譯過程中所用到的一些臨時檔案, 這些檔案不只佔硬碟空間,而且也可能會在該 port 升級新版時, 造成不必要的困擾。

# make clean
===>  Cleaning for lsof-4.57
#

注意:

make install clean 就可以一口氣完成剛所說 makemake installmake clean 這三個步驟了。

注意:

有些 shell 會依據 PATH 環境變數的路徑, 把那些路徑的執行檔 cache 起來,來加速搜尋執行檔。 如果你用的是這類的 shell,那麼在裝完 port 後需要打 rehash 指令,才能執行新裝的執行檔,而 rehash 指令可以在 tcsh 之類的 shell 上使用,若是 sh 的話,則是 hash -r。 詳情請參閱你所使用的 shell 相關文件。

有些由所謂 third-party 所發行的 DVD-ROM 產品,像是 FreeBSD Mall 所發行的 FreeBSD Toolkit 會包括 distfiles 檔案, 這些檔案可用來搭配 Ports Collection。 把 DVD-ROM 掛載在 /cdrom。 若使用其他掛載點的話,要記得設定 CD_MOUNTPTS 環境變數為相對應的掛載點。 如此一來,光碟上若有所需的 distfiles 就會自動使用光碟的檔案。

注意:

請注意,有少數 port 並不允許透過光碟來發佈檔案。 可能的原因有:需先填註冊單才能下載或散佈檔案,或其他原因。 如果想安裝在光碟上沒附上的 port,就需連上網路才能繼續進行安裝。

ports 系統採用 fetch(1) 來下載檔案, 它有許多可調整的環境變數,包括: FTP_PASSIVE_MODEFTP_PROXYFTP_PASSWORD。 如果是處於有防火牆的環境, 或者需要使用 FTP/HTTP proxy,那麼就需要設定這些變數。 使用細節請參閱 fetch(3) 說明。

若無法隨時一直上網的話,那麼可以利用 make fetch。 只要在 port 的最上層路徑(/usr/ports) 打這指令,那麼所有需要用到的檔案都會下載。 這指令也可以在下層目錄使用,例如: /usr/ports/net。 請注意,若該 port 有相依的 library 或者其他 port 的話, 那麼它並不會跟著一起下載其他所相依的檔案。 若想一次下載所有相依的 port 所有檔案,那麼指令參數請改用 fetch-recursive 而非 fetch

注意:

可以在某類別或最上層路徑打 make 指令來編譯所有的 port,或者以上述的 make fetch 指令來下載所有檔案。 然而,這樣是相當危險,因為有些 port 不能並存。 也有另一種情況,有些 port 可能會以相同檔名, 但是實際上卻是不同內容的檔案。

在某些罕見情況,可能需加上 MASTER_SITES (檔案的原始下載處)之外的下載點,以下載所需的檔案。 可以用下列指令,來更改預設的 MASTER_SITES 下載點:

# cd /usr/ports/directory
# make MASTER_SITE_OVERRIDE= \
ftp://ftp.FreeBSD.org/pub/FreeBSD/ports/distfiles/ fetch

上面這例子,是把 MASTER_SITES 改設 ftp.FreeBSD.org/pub/FreeBSD/ports/distfiles/ 為下載點。

注意:

有些 port 允許(或要求)您得指定編譯選項, 以啟用、停用該軟體中非必須的功能、安全選項以及其他可自訂的選項。 具有代表性的包括了 www/mozillasecurity/gpgmemail/sylpheed-claws。 若有這類選項時,通常在編譯時會出現相關提示訊息。

4.5.1.1. 更改(Override)預設的 Ports 目錄

有時候,會發現到使用其他目錄作為 port、distfiles 目錄可能相當有用(甚至是必須),可以設定 PORTSDIRPREFIX 環境變數以修改預設的 port 目錄。舉例:

# make PORTSDIR=/usr/home/example/ports install

以上會在 /usr/home/example/ports 內進行編譯, 並把所有檔案安裝到 /usr/local 內。

# make PREFIX=/usr/home/example/local install

則會在 /usr/ports 目錄內編譯, 並把所有檔案安裝到 /usr/home/example/local 內。

當然囉,

# make PORTSDIR=../ports PREFIX=../local install

則會同時包含兩種設定(還有很多變化以致無法在本頁全部都有寫到, 但您應該已經有抓到大概概念了吧)。

此外,這些變數也以作為環境變數來設定。 請依您所使用的 shell 去參閱相關說明,以瞭解如何設定。

4.5.1.2. 處理 imake

有些 port 會使用 imake(X Window 系統的一部份) 無法正常運用 PREFIX 變數, 它們會堅持把檔案都安裝到 /usr/X11R6 目錄。 同樣地,也有一些 Perl port 會忽略 PREFIX 並把檔案安裝到 Perl 目錄架構內。 讓這些 ports respect PREFIX 是相當困難,甚至是不可能的事。

4.5.1.3. 重新設定 Ports 選項

在編譯某些 port 時會出現選單畫面(ncurses-based), 可以用來選擇安裝選項。 通常裝好該 port 之後,便不太會需要重加、 移除、更改一些當初安裝的選項。 但日後若有需要的話, 也有許多方式可以調整這些選項。 其中一種方式便是切到該 port 目錄, 並打 make config 即可再次回到選項畫面去作調整。 另外還可用 make showconfig 以顯示該 port 安裝時所用的選項。 也可以用 make rmconfig 來把所有選項回到初始設定。 這些選項跟其他動作都可參閱 ports(7) 內的詳細說明。

4.5.2. 移除已安裝的 Ports

現在您已經知道如何安裝 port,而開始想瞭解如何移除。 比如裝了一個 port 後才意識到裝錯 port 了。 在此,我們將移除前面例子所裝的那個 port (沒仔細注意的話,我們再提醒一下就是 lsof)。 跟移除 package 時相當類似,都是使用 pkg_delete(1) 指令:

# pkg_delete lsof-4.57

4.5.3. 升級已安裝的 Ports

首先,用 pkg_version(1) 指令來列出目前 Ports Collection 中提供了那些可升級的 port 版本:

# pkg_version -v

4.5.3.1. /usr/ports/UPDATING

每次更新完 Ports Collection 之後,請務必記得在升級 port 前, 先看看 /usr/ports/UPDATING, 這裡會寫升級方面的各式問題,比如:檔案格式改變、變更設定檔位置、 與舊版不相容的問題等,以及怎麼解決的完整步驟。

UPDATING 內容與你看到的其他文件有些不同 、相衝的話, 那麼請以 UPDATING 為準。

4.5.3.2. 以 Portupgrade 來升級已安裝的 Ports

portupgrade 可以輕鬆升級已裝的軟體。 該工具可從 ports-mgmt/portupgrade port 安裝, 安裝方式就如同其他 port 一樣,用 make install clean 指令就可以了:

# cd /usr/ports/ports-mgmt/portupgrade
# make install clean

首先最好先以 pkgdb -F 來掃瞄已裝的 ports 資料庫是否有誤,並修正有問題的地方。 在每次做升級之前,最好定期做一下 pkgdb -F 動作會較為妥當。

portupgrade -a 的話, portupgrade 會升級系統上所有已裝的過舊 ports。 若用 -i 則在升級每個 port 過程當中, 會要求確認相關動作是否符合所需。

# portupgrade -ai

若只想升級某特定程式而非全部,那麼可以用 portupgrade pkgname 來做指定。 若想要 portupgrade 優先升級某 port 所相依的相關套件,則請用 -R 參數即可。

# portupgrade -R firefox

若要用 package 而非 port 來安裝,則需指定 -P 才可以。 若有指定這選項,則 portupgrade 會搜尋 PKG_PATH 變數所指定的本機目錄, 若找不到則透過網路來下載安裝。 若本機跟網路都沒有可用的 package 的話,則 portupgrade 會使用 port 方式安裝。 若不想如此又變成使用 port 方式安裝,則用 -PP 即可強制避免使用 port 方式安裝。

# portupgrade -PP gnome2

若只想下載 distfiles(或者若指定 -P 的話,則是 package)而不想編譯或安裝檔案,可以使用 -F。 詳情請參閱 portupgrade(1) 的說明。

4.5.3.3. 以 Portmanager 來升級已安裝的 Ports

Portmanager 也可以用來輕鬆升級已裝的軟體。 該工具可從 ports-mgmt/portmanager port 安裝:

# cd /usr/ports/ports-mgmt/portmanager
# make install clean

所有已裝的軟體,都可以輕鬆用類似下列指令來升級:

# portmanager -u

此外,使用參數可以改為 -ui,如此一來 Portmanager 在升級一些有特殊選項的軟體時 ,就會詢問該如何升級。 Portmanager 也可以用來裝新 port。與以往常用的 make install clean 指令不同之處在於: 它會先升級你要裝的 port 所相依的所有 ports,然後才開始編譯、 安裝要裝的 port。

# portmanager x11/gnome2

若要裝的 port 之軟體相依關係有問題時,也可以用 Portmanager 使它們重歸正軌。 而 Portmanager 解決相依問題完畢之後,該 port 也會重新編譯,以因應正確的相依關係。

# portmanager graphics/gimp -f

其餘運用法門,請參閱 portmanager(1) 說明。

4.5.4. Ports 與硬碟空間

因為使用 Ports Collection 遲早可能會用光硬碟空間, 所以在裝完軟體後,記得要以 make clean 指令來清除臨時的 work 目錄。 此外,可以用下列指令來清除整個 Ports Collection 內的臨時目錄:

# portsclean -C

ports 用久了,您可能會在 distfiles 目錄內會累積著許多的原始碼檔案。 可以手動刪除這些檔案, 或者用下列指令來清除所有 port 都不使用的舊檔:

# portsclean -D

或者要清除所有已裝的 port 都不再使用的舊檔:

# portsclean -DD

注意:

portsclean 這工具乃是 portupgrade 套件的一部分。

不要忘了移除那些已經安裝,但不再需要用到的 ports。 有個 ports-mgmt/pkg_cutleaves port,正是可自動完成這功能的好工具。

4.6. 安裝之後,有什麼後續注意事項嗎?

通常,安裝完軟體後,我們可以閱讀所附的一些文件,或需要編輯設定檔, 來確保這個軟體能順利運作,或在機器開機的時候啟動(如果是 daemon 的話) 等等。

不同的軟體會有不同的設定步驟。不管怎樣,如果裝好了軟體, 但是不知道下一步怎麼辦的時候, 可以試試看這些小技巧:

  • 善用 pkg_info(1) ,這指令可以顯示:透過套件管理系統 (Packages/Ports)裝了哪些軟體、檔案裝在哪邊。舉例來說,若剛裝了 FooPackage (版本 1.0.0),那麼下面這指令:

    # pkg_info -L foopackage-1.0.0 | less

    就會顯示這軟體所安裝的檔案清單。 請特別注意在 man/ 目錄內是說明檔、 etc/ 目錄內是設定檔、 doc/ 目錄內是完整文件。

    若不確定已裝的套件版本為何,可以用類似下列指令來查:

    # pkg_info | grep -i foopackage

    以上將會搜尋所有已裝的套件,列出有符合 foopackage 的套件名稱。 請自行依需求,修改 foopackage 為想找的套件名稱。

  • 一旦確認該程式的線上說明有安裝,就可以用 man(1) 來翻閱。 同樣地,若該程式有提供的話,也可以參考設定檔樣本,以及其他文件。

  • 若該程式有官網的話,還可以透過網站來找文件、常見問答集(FAQ)等。 若不知道網址,請用下列指令:

    # pkg_info foopackage-1.0.0

    若該程式有官網的話,則會有一行 WWW: 開頭的出現,這行會列出該程式的官網網址(URL)。

  • Port 若須在開機時就會啟動(就像 Internet 主機),通常都會安裝 script 到 /usr/local/etc/rc.d 目錄。 您可以檢閱這 script 的正確與否,或若有需要,也可以修改、改名。 詳情請參閱 啟動 Services

4.7. 如何處理爛掉(Broken)的 Ports?

如果發現某個 port 無法順利安裝、運作, 有幾種方法可以試試看:

  1. Problem Report 資料庫 中挖寶看看,說不定已經有人送可用的 patch 上去囉, 那麼或許就可以順利解決問題哩。

  2. 向該 port 的 maintainer 尋求協助:請打 make maintainer 或翻閱 Makefile 以查詢 maintainer 的 email address。記得寄信給 maintainer 時,要附註該 port 的名稱、版本(或是把 Makefile 內的 $FreeBSD: 那一整行附上) 以及相關錯誤訊息。

    注意:

    有些 port 不是由專門的單一 maintainer 負責,而是透過 mailing list 的專題討論。許多(但非全部)的聯絡 email 格式通常是 。發問時,請記得把『freebsd-list名稱』改為相關討論的 mailing list 名稱。

    尤其當 port 的 maintainer 欄位是 時,事實上已經沒人當該 port maintainer 了。 因此若該 port 仍有修正或其他技術支援的話,相關討論都會在 freebsd-ports 郵遞論壇上出現。 喔,對了,如果有熟悉該軟體者,志願當該 port maintainer 的話,我們也都很歡迎您的加入喔。

    若 port maintainer 沒有回覆您的信件, 則可以用 send-pr(1) 來提交問題報告 PR。(請參閱 Writing FreeBSD Problem Reports)。

  3. 試試看修正它吧! Porter's Handbook 包括了 Ports 架構的細節部份,這些書中內容有助您修好有問題的 port 甚至提交自己的 port﹗

  4. 從較近的 FTP 站點下載編譯好的 package。 package collection 的最上游站是在 ftp.FreeBSD.org 上的 packages 目錄內,但請記得先檢查是否已有 local mirror 站! 通常情況下這些 package 都可以直接使用, 而且應該比自行編譯快一些。 用 pkg_add(1) 即可順利安裝 package 。

章 5. X Window 視窗系統

Updated for X.Org's X11 server by Ken TomMarc Fonvieille.

5.1. 概述

FreeBSD 使用 X11 來提供使用者相當好用的 GUI 介面。 X11 是 X Window 系統,包括 Xorg 以及 XFree86 實作的自由軟體版本 (以及其他未在本章有介紹的軟體)。 FreeBSD 一直到 FreeBSD 5.2.1-RELEASE 都仍可在預設的安裝程式內去裝 XFree86 (由 The XFree86™ Project, Inc 發行的 X11 server)。 而 FreeBSD 5.3-RELEASE 起,預設的 X11 改為 Xorg(由 X.Org 基金會所開發的 X11 server,並採用與 FreeBSD 相當類似的 license)。 此外,當然也有商業 X servers 的 FreeBSD 版。

本章主要是介紹 X11 (主要著重於 Xorg 7.7 版部分)的安裝與設定。 若欲瞭解 XFree86 的詳細資料(早期的 FreeBSD 內, XFree86 乃是預設的 X11 套件),請參閱舊版的 FreeBSD Handbook,網址為 http://docs.FreeBSD.org/doc/

欲知 X11 對於顯示方面硬體的支援情況,請參閱 Xorg 網站。

讀完這章,您將了解:

  • X Window 系統的各組成部份,以及它們是如何相互運作。

  • 如何安裝、設定 X11。

  • 如何安裝並使用不同的 window managers。

  • 如何在 X11 上使用 TrueType® 字型。

  • 如何設定系統以使用圖形登入介面。 (XDM)

在開始閱讀這章之前,您需要︰

5.2. 瞭解 X 的世界

第一次接觸 X 的人,大概都會有些震撼,尤其是熟悉其他 GUI 介面(像是 Microsoft® Windows® 或 Mac OS®)的使用者。

雖然 X 各元件的所有細節及運作方式,並不是必須要知道的。 但對它們有些基本概念會更容易上手。

5.2.1. 為何叫做 X?

X 並非 UNIX® 上第一套視窗系統,但它卻是最廣為流傳運用。 原本的 X 研發團隊在研發 X 之前有開發另一套視窗系統。 那套系統叫做 W(取 Window 的第一個字)。 而 X 則是 W 之後的下一個羅馬字母。

X 亦被稱之為 XX Window SystemX11,以及其他一些詞彙。 使用 X Windows 這字眼來稱呼 X11,可能會讓有些人不爽;這部分細節可參閱 X(7) 說明。

5.2.2. X 的 Client/Server 架構

X 一開始是設計為網路架構環境,並採用 client-server 架構。

在 X 架構下, X server 是在有鍵盤、螢幕、滑鼠的電腦上運作。 而 server 部份則是負責像是顯示部份的管理、 處理來自鍵盤、滑鼠及其他設備(比方像是以繪圖板來輸入、 或者是顯示到投影機)的輸入等等, 每個 X 程式(像是 XTerm,或 Netscape®)都是 client。 client 會傳訊息到 server 上,比如:Please draw a window at these coordinates,接著 server 會傳回訊息,比如: The user just clicked on the OK button

在家庭或小辦公室環境,通常 X server 跟 X client 都是在同一台電腦上執行的。 然而,也可以在比較爛的桌機上執行 X server, 並在比較強、比較貴的電腦上跑 X 程式(client)來做事情。 在這種場景,X client 與 server 之間的溝通就需透過網路來進行。

這點可能會讓有些人產生困惑,因為 X 術語與他們原本的認知剛好相反。 他們原本以為 X server 是要在最強悍的機器上跑才行,而 X client 則是在他們桌機上面跑。 實際上卻不是這樣。

有點相當重要,請記住 X server 是在有接螢幕、鍵盤的機器上運作, 而 X client 則是顯示這些視窗的程式。

協定(protocol)內並無強制規定 client 以及 server 兩邊機器都得是同一作業系統,或者得是同型機器才可以。 換句話說,也可以在 Microsoft® Windows® 或蘋果電腦(Apple)的 Mac OS® 上跑 X server,而且可以透過許多免費或商業軟體完成這些安裝、設定。

5.2.3. The Window Manager

X 設計哲學與 UNIX® 設計哲學相當類似,都是 tools, not policy。 也就是說,X 不會試圖強制規定某任務應該要如何完成,而是只提供使用者一些工具, 至於如何運用這些工具,則是使用者本身的事了。

X 延續這哲學,它並不規定:螢幕上的視窗該長什麼樣、要如何移動滑鼠指標、 該用什麼組合鍵來切換各視窗(比如:在 Microsoft® Windows® 的 Alt+Tab鍵)、各視窗的標題列長相,以及是否該有關閉鈕等等。

事實上,X 把這部分交給所謂的 Window Manager 來管理。 有一堆 window manager 程式,像是: AfterStepBlackboxctwmEnlightenmentfvwmSawfishtwmWindow Maker 等等。每一種 window manager 都提供不同的使用經驗; 有些還可使用 virtual desktops(虛擬桌面) ;有些則可自訂組合鍵來管理桌面;有些會有 Start(開始) 鈕或其他類似設計;有些則是 可更換佈景主題, 可自行安裝新的佈景主題以更換外觀。 這些跟其他的 window manager 在 Ports Collection 內的 x11-wm 目錄內都有。

此外,KDEGNOME 桌面環境則有其自屬並整合完整的 window manager。

每個 window manager 也各有其不同的設定機制;有些需手動寫設定檔, 而有的則可透過 GUI 工具來完成大部分的設定。舉個例子: Sawfish 就有以 Lisp 語言寫的設定檔。

Focus Policy:

window manager 的另一特色就是負責滑鼠指標的 focus policy。 每一種視窗系統都需要選擇作用視窗的方式 ,以接受鍵盤輸入,以及決定目前哪個視窗是處於使用中的狀態。

通常較為人熟悉的 focus policy 叫做 click-to-focus, 這是 Microsoft® Windows® 所採用的模式,也就是指標在該視窗按一下的話, 該視窗就會處於使用中的狀態。

X 並不支援一些特殊的 focus policy。 換句話說,window manager 會控制哪個視窗在何時是作用中。 不同的 window manager 有不同的支援方式。 但它們都支援 click-to-focus, 而且大多數都有支援多種方式。

以下是目前最流行的 focus policy:

focus-follows-mouse

滑鼠移到哪個視窗就是使用該視窗。 該視窗不一定位於其他視窗上面, 但只要把滑鼠移到該視窗就可以改變作用中的視窗, 而不需在它上面點擊。

sloppy-focus

該 policy 是針對 focus-follows-mouse 的小小延伸。 對於 focus-follows-mouse 而言,若把游標移到最初的視窗(或桌面), 那所有其他視窗都會處於非作用中,而且所有鍵盤輸入也會失效。 若是選用 sloppy-focus,則只有在游標移到新視窗時, 作用中的視窗才會變成新的, 而只離開目前作用中的視窗仍不會改變作用狀態。

click-to-focus

由游標點擊才會決定作用中的視窗。 並且該視窗會被 raised(凸顯) 到所有其他視窗之前, 即使游標移到其他視窗,所有的鍵盤輸入仍會由該視窗所接收。

許多 window manager 也支援其他 policy,與這些相比起來又有些不同, 細節部分請參閱該 window manager 的文件說明。

5.2.4. Widgets

The X approach of providing tools and not policy extends to the widgets seen on screen in each application.

Widget is a term for all the items in the user interface that can be clicked or manipulated in some way; buttons, check boxes, radio buttons, icons, lists, and so on. Microsoft® Windows® calls these controls.

Microsoft® Windows® and Apple's Mac OS® both have a very rigid widget policy. Application developers are supposed to ensure that their applications share a common look and feel. With X, it was not considered sensible to mandate a particular graphical style, or set of widgets to adhere to.

As a result, do not expect X applications to have a common look and feel. There are several popular widget sets and variations, including the original Athena widget set from MIT, Motif® (on which the widget set in Microsoft® Windows® was modeled, all bevelled edges and three shades of grey), OpenLook, and others.

Most newer X applications today will use a modern-looking widget set, either Qt, used by KDE, or GTK+, used by the GNOME project. In this respect, there is some convergence in look-and-feel of the UNIX® desktop, which certainly makes things easier for the novice user.

5.3. 安裝 X11

Xorg 是 FreeBSD 預設的 X11 實作。 Xorg 是由 X.Org 基金會所發行之開放源碼軟體 X Window 系統實作的 X server。 Xorg 乃是以 XFree86™ 4.4RC2 以及 X11R6.6 為基礎所產生的。 目前 FreeBSD Ports Collection 內的 Xorg 版本為 7.7。

從 Ports Collection 來安裝 Xorg 的安裝方式:

# cd /usr/ports/x11/xorg
# make install clean

注意:

若要編譯完整的 Xorg, 請先確認至少有 4 GB 的磁碟空間。

此外 X11 也可直接透過 package 方式來安裝,可使用 pkg_add(1) 來安裝編譯好的 X11 套件,記得在透過網路安裝時不要指定版本即可, pkg_add(1) 會自動抓該套件最新版的套件回來。

若要自動透過 package 方式來裝 Xorg ,直接打下面這行即可:

# pkg_add -r xorg

注意:

上面的例子會裝完整的 X11 套件,包括 server、client、字型等。 此外,還有其他的 X11 子套件可透過 package 或 port 方式來單獨安裝。

本章其餘部分將介紹如何設定 X11, 以及如何打造高生產力的桌面環境。

5.4. 設定 X11

Contributed by Christopher Shumway.

5.4.1. 在開始之前

在開始設定 X11 之前,要先瞭解所要裝的機器資料為何:

  • 螢幕規格

  • 顯示卡的晶片規格

  • 顯示卡的記憶體容量

X11 會依螢幕規格來決定解析度以及更新頻率。 這些規格通常可從螢幕所附的文件或廠商網站上取得。 最重要的是要知道水平、垂直更新頻率為何。

而顯示卡晶片則決定 X11 要用哪一種驅動程式模組。 大多數的晶片都可以自動偵測,但最好還是要知道是何種晶片, 以免萬一自動偵測失敗。

Video memory on the graphic adapter determines the resolution and color depth which the system can run at. This is important to know so the user knows the limitations of the system.

5.4.2. 設定 X11

Xorg 自 7.3 版起不再需任何設定檔,只要打下列即可:

% startx

若這指令不行或預設設定無法使用,那麼就需要手動設定 X11。 設定 X11 需要幾個步驟,首先是以系統管理者帳號來建立初始設定檔:

# Xorg -configure

這會在 /root 目錄內產生 xorg.conf.new 設定檔(無論是用 su(1) 或直接登入為 root,都會改變 root 預設的 $HOME 環境變數)。 X11 程式接著會偵測系統的顯示卡相關硬體,並將偵測到硬體訊息寫入設定檔, 以便載入正確的驅動程式。

下一步是測試現有的設定檔,以便確認 Xorg 可以與顯示卡、螢幕相關硬體正確運作:

# Xorg -config xorg.conf.new

若看得到一堆黑灰夾雜的網格畫面,以及 X 形的滑鼠游標, 那麼設定檔就是成功的。 要退出測試,只要同時按下 Ctrl+Alt+Backspace 即可。

注意:

若滑鼠不正確運作,那麼需要先對其作設定。

Next, tune the xorg.conf.new configuration file to taste. Open the file in a text editor such as emacs(1) or ee(1). First, add the frequencies for the target system's monitor. These are usually expressed as a horizontal and vertical synchronization rate. These values are added to the xorg.conf.new file under the "Monitor" section:

Section "Monitor"
        Identifier   "Monitor0"
        VendorName   "Monitor Vendor"
        ModelName    "Monitor Model"
        HorizSync    30-107
        VertRefresh  48-120
EndSection

The HorizSync and VertRefresh keywords may be missing in the configuration file. If they are, they need to be added, with the correct horizontal synchronization rate placed after the HorizSync keyword and the vertical synchronization rate after the VertRefresh keyword. In the example above the target monitor's rates were entered.

X allows DPMS (Energy Star) features to be used with capable monitors. The xset(1) program controls the time-outs and can force standby, suspend, or off modes. If you wish to enable DPMS features for your monitor, you must add the following line to the monitor section:

        Option       "DPMS"

While the xorg.conf.new configuration file is still open in an editor, select the default resolution and color depth desired. This is defined in the "Screen" section:

Section "Screen"
        Identifier "Screen0"
        Device     "Card0"
        Monitor    "Monitor0"
        DefaultDepth 24
        SubSection "Display"
                Viewport  0 0
                Depth     24
                Modes     "1024x768"
        EndSubSection
EndSection

The DefaultDepth keyword describes the color depth to run at by default. This can be overridden with the -depth command line switch to Xorg(1). The Modes keyword describes the resolution to run at for the given color depth. Note that only VESA standard modes are supported as defined by the target system's graphics hardware. In the example above, the default color depth is twenty-four bits per pixel. At this color depth, the accepted resolution is 1024 by 768 pixels.

Finally, write the configuration file and test it using the test mode given above.

注意:

One of the tools available to assist you during troubleshooting process are the X11 log files, which contain information on each device that the X11 server attaches to. Xorg log file names are in the format of /var/log/Xorg.0.log. The exact name of the log can vary from Xorg.0.log to Xorg.8.log and so forth.

If all is well, the configuration file needs to be installed in a common location where Xorg(1) can find it. This is typically /etc/X11/xorg.conf or /usr/local/etc/X11/xorg.conf.

# cp xorg.conf.new /etc/X11/xorg.conf

The X11 configuration process is now complete. Xorg 目前可透過 startx(1) 來啟動之。 The X11 server may also be started with the use of xdm(1).

注意:

There is also a graphical configuration tool, xorgcfg(1), which comes with the X11 distribution. It allows you to interactively define your configuration by choosing the appropriate drivers and settings. This program can be invoked from the console, by typing the command xorgcfg -textmode. For more details, refer to the xorgcfg(1) manual pages.

Alternatively, there is also a tool called xorgconfig(1). This program is a console utility that is less user friendly, but it may work in situations where the other tools do not.

5.4.3. 進階設定專欄

5.4.3.1. 設定 Intel® i810 繪圖晶片組

Configuration with Intel® i810 integrated chipsets requires the agpgart AGP programming interface for X11 to drive the card. 詳情請參閱 agp(4) 說明。

This will allow configuration of the hardware as any other graphics board. Note on systems without the agp(4) driver compiled in the kernel, trying to load the module with kldload(8) will not work. This driver has to be in the kernel at boot time through being compiled in or using /boot/loader.conf.

5.4.3.2. 為寬螢幕打造更舒適環境

本節假設各位已經有些微進階設定的功力。 如果試著使用上述設定工具會有問題的話,請多利用相關 log 檔 (會記錄相關訊息)以便找出解法。 找尋解法過程中,可能會需要用到文字編輯器作為輔助。

目前的寬螢幕 (WSXGA, WSXGA+, WUXGA, WXGA, WXGA+ 等) 都有支援 16:10 及 10:9 比例,以及一些可能有問題的比例。 以下是一些常見的 16:10 螢幕解析度:

  • 2560x1600

  • 1920x1200

  • 1680x1050

  • 1440x900

  • 1280x800

某方面而言,要增加這些解析度設定也是相當容易的, 只要在 Section "Screen" 內的 Mode 加上去就好,比如:

Section "Screen"
Identifier "Screen0"
Device     "Card0"
Monitor    "Monitor0"
DefaultDepth 24
SubSection "Display"
	Viewport  0 0
	Depth     24
	Modes     "1680x1050"
EndSubSection
EndSection

Xorg 可以透過 I2C/DDC 來得知該寬螢幕所支援的解析度等相關資訊, 因此就能正確偵測出該螢幕所能支援的頻率、解析度。

若驅動程式並未包括 ModeLine 訊息的話, 那麼就要為 Xorg 做些設定才行。 我們可以透過 /var/log/Xorg.0.log 檔來取得 ModeLine 相關設定資料,即可讓螢幕正常顯示。 應該可以看到類似下面的訊息:

(II) MGA(0): Supported additional Video Mode:
(II) MGA(0): clock: 146.2 MHz   Image Size:  433 x 271 mm
(II) MGA(0): h_active: 1680  h_sync: 1784  h_sync_end 1960 h_blank_end 2240 h_border: 0
(II) MGA(0): v_active: 1050  v_sync: 1053  v_sync_end 1059 v_blanking: 1089 v_border: 0
(II) MGA(0): Ranges: V min: 48  V max: 85 Hz, H min: 30  H max: 94 kHz, PixClock max 170 MHz

這些訊息被稱為 EDID 訊息。 可以藉由這些資料, 搭配下列的正確順序來產生 ModeLine 設定:

 ModeLine <name> <clock> <4 horiz. timings> <4 vert. timings>

所以這個案例 Section "Monitor"ModeLine 就會是像下面這樣:

Section "Monitor"
Identifier      "Monitor1"
VendorName      "Bigname"
ModelName       "BestModel"
ModeLine        "1680x1050" 146.2 1680 1784 1960 2240 1050 1053 1059 1089
Option          "DPMS"
EndSection

這樣子就簡單完成了,X 視窗就可以打造為新的寬螢幕環境囉。

5.5. 在 X11 中使用字型

Contributed by Murray Stokely.

5.5.1. Type1 規格的字型

The default fonts that ship with X11 are less than ideal for typical desktop publishing applications. Large presentation fonts show up jagged and unprofessional looking, and small fonts in Netscape® are almost completely unintelligible. However, there are several free, high quality Type1 (PostScript®) fonts available which can be readily used with X11. For instance, the URW font collection (x11-fonts/urwfonts) includes high quality versions of standard type1 fonts (Times Roman®, Helvetica®, Palatino® and others). The Freefonts collection (x11-fonts/freefonts) includes many more fonts, but most of them are intended for use in graphics software such as the Gimp, and are not complete enough to serve as screen fonts. In addition, X11 can be configured to use TrueType® fonts with a minimum of effort. For more details on this, see the X(7) manual page or the section on TrueType® fonts.

To install the above Type1 font collections from the ports collection, run the following commands:

# cd /usr/ports/x11-fonts/urwfonts
# make install clean

And likewise with the freefont or other collections. To have the X server detect these fonts, add an appropriate line to the X server configuration file (/etc/X11/xorg.conf), which reads:

FontPath "/usr/local/lib/X11/fonts/URW/"

Alternatively, at the command line in the X session run:

% xset fp+ /usr/local/lib/X11/fonts/URW
% xset fp rehash

This will work but will be lost when the X session is closed, unless it is added to the startup file (~/.xinitrc for a normal startx session, or ~/.xsession when logging in through a graphical login manager like XDM). A third way is to use the new /usr/local/etc/fonts/local.conf file: see the section on anti-aliasing.

5.5.2. TrueType® 規格的字型

Xorg has built in support for rendering TrueType® fonts. There are two different modules that can enable this functionality. The freetype module is used in this example because it is more consistent with the other font rendering back-ends. To enable the freetype module just add the following line to the "Module" section of the /etc/X11/xorg.conf file.

Load  "freetype"

Now make a directory for the TrueType® fonts (for example, /usr/local/lib/X11/fonts/TrueType) and copy all of the TrueType® fonts into this directory. Keep in mind that TrueType® fonts cannot be directly taken from a Macintosh®; they must be in UNIX®/MS-DOS®/Windows® format for use by X11. Once the files have been copied into this directory, use ttmkfdir to create a fonts.dir file, so that the X font renderer knows that these new files have been installed. ttmkfdir is available from the FreeBSD Ports Collection as x11-fonts/ttmkfdir.

# cd /usr/local/lib/X11/fonts/TrueType
# ttmkfdir -o fonts.dir

Now add the TrueType® directory to the font path. This is just the same as described above for Type1 fonts, that is, use

% xset fp+ /usr/local/lib/X11/fonts/TrueType
% xset fp rehash

or add a FontPath line to the xorg.conf file.

That's it. Now Netscape®, Gimp, StarOffice, and all of the other X applications should now recognize the installed TrueType® fonts. Extremely small fonts (as with text in a high resolution display on a web page) and extremely large fonts (within StarOffice) will look much better now.

5.5.3. Anti-Aliased 規格的字型

Updated by Joe Marcus Clarke.

Anti-aliasing has been available in X11 since XFree86 4.0.2. However, font configuration was cumbersome before the introduction of XFree86 4.3.0. Beginning with XFree86 4.3.0, all fonts in X11 that are found in /usr/local/lib/X11/fonts/ and ~/.fonts/ are automatically made available for anti-aliasing to Xft-aware applications. Not all applications are Xft-aware, but many have received Xft support. Examples of Xft-aware applications include Qt 2.3 and higher (the toolkit for the KDE desktop), GTK+ 2.0 and higher (the toolkit for the GNOME desktop), and Mozilla 1.2 and higher.

In order to control which fonts are anti-aliased, or to configure anti-aliasing properties, create (or edit, if it already exists) the file /usr/local/etc/fonts/local.conf. Several advanced features of the Xft font system can be tuned using this file; this section describes only some simple possibilities. For more details, please see fonts-conf(5).

This file must be in XML format. Pay careful attention to case, and make sure all tags are properly closed. The file begins with the usual XML header followed by a DOCTYPE definition, and then the <fontconfig> tag:

      <?xml version="1.0"?>
      <!DOCTYPE fontconfig SYSTEM "fonts.dtd">
      <fontconfig>
    

As previously stated, all fonts in /usr/local/lib/X11/fonts/ as well as ~/.fonts/ are already made available to Xft-aware applications. If you wish to add another directory outside of these two directory trees, add a line similar to the following to /usr/local/etc/fonts/local.conf:

<dir>/path/to/my/fonts</dir>

After adding new fonts, and especially new font directories, you should run the following command to rebuild the font caches:

# fc-cache -f

Anti-aliasing makes borders slightly fuzzy, which makes very small text more readable and removes staircases from large text, but can cause eyestrain if applied to normal text. To exclude font sizes smaller than 14 point from anti-aliasing, include these lines:

        <match target="font">
            <test name="size" compare="less">
                <double>14</double>
            </test>
            <edit name="antialias" mode="assign">
                <bool>false</bool>
            </edit>
        </match>
        <match target="font">
            <test name="pixelsize" compare="less" qual="any">
                <double>14</double>
            </test>
            <edit mode="assign" name="antialias">
                <bool>false</bool>
            </edit>
        </match>

Spacing for some monospaced fonts may also be inappropriate with anti-aliasing. This seems to be an issue with KDE, in particular. One possible fix for this is to force the spacing for such fonts to be 100. Add the following lines:

       <match target="pattern" name="family">
           <test qual="any" name="family">
               <string>fixed</string>
           </test>
           <edit name="family" mode="assign">
               <string>mono</string>
           </edit>
        </match>
        <match target="pattern" name="family">
            <test qual="any" name="family">
                <string>console</string>
            </test>
            <edit name="family" mode="assign">
                <string>mono</string>
            </edit>
        </match>

(this aliases the other common names for fixed fonts as "mono"), and then add:

         <match target="pattern" name="family">
             <test qual="any" name="family">
                 <string>mono</string>
             </test>
             <edit name="spacing" mode="assign">
                 <int>100</int>
             </edit>
         </match>      

Certain fonts, such as Helvetica, may have a problem when anti-aliased. Usually this manifests itself as a font that seems cut in half vertically. At worst, it may cause applications such as Mozilla to crash. To avoid this, consider adding the following to local.conf:

         <match target="pattern" name="family">
             <test qual="any" name="family">
                 <string>Helvetica</string>
             </test>
             <edit name="family" mode="assign">
                 <string>sans-serif</string>
             </edit>
         </match>        

Once you have finished editing local.conf make sure you end the file with the </fontconfig> tag. Not doing this will cause your changes to be ignored.

The default font set that comes with X11 is not very desirable when it comes to anti-aliasing. A much better set of default fonts can be found in the x11-fonts/bitstream-vera port. This port will install a /usr/local/etc/fonts/local.conf file if one does not exist already. If the file does exist, the port will create a /usr/local/etc/fonts/local.conf-vera file. Merge the contents of this file into /usr/local/etc/fonts/local.conf, and the Bitstream fonts will automatically replace the default X11 Serif, Sans Serif, and Monospaced fonts.

Finally, users can add their own settings via their personal .fonts.conf files. To do this, each user should simply create a ~/.fonts.conf. This file must also be in XML format.

One last point: with an LCD screen, sub-pixel sampling may be desired. This basically treats the (horizontally separated) red, green and blue components separately to improve the horizontal resolution; the results can be dramatic. To enable this, add the line somewhere in the local.conf file:

         <match target="font">
             <test qual="all" name="rgba">
                 <const>unknown</const>
             </test>
             <edit name="rgba" mode="assign">
                 <const>rgb</const>
             </edit>
         </match>
       

注意:

Depending on the sort of display, rgb may need to be changed to bgr, vrgb or vbgr: experiment and see which works best.

Anti-aliasing should be enabled the next time the X server is started. However, programs must know how to take advantage of it. At present, the Qt toolkit does, so the entire KDE environment can use anti-aliased fonts. GTK+ and GNOME can also be made to use anti-aliasing via the Font capplet (see 節 5.7.1.3, “Anti-aliased Fonts with GNOME” for details). By default, Mozilla 1.2 and greater will automatically use anti-aliasing. To disable this, rebuild Mozilla with the -DWITHOUT_XFT flag.

5.6. The X Display Manager

Contributed by Seth Kingsley.

5.6.1. Overview

The X Display Manager (XDM) is an optional part of the X Window System that is used for login session management. This is useful for several types of situations, including minimal X Terminals, desktops, and large network display servers. Since the X Window System is network and protocol independent, there are a wide variety of possible configurations for running X clients and servers on different machines connected by a network. XDM provides a graphical interface for choosing which display server to connect to, and entering authorization information such as a login and password combination.

Think of XDM as providing the same functionality to the user as the getty(8) utility (see 節 25.3.2, “Configuration” for details). That is, it performs system logins to the display being connected to and then runs a session manager on behalf of the user (usually an X window manager). XDM then waits for this program to exit, signaling that the user is done and should be logged out of the display. At this point, XDM can display the login and display chooser screens for the next user to login.

5.6.2. Using XDM

The XDM daemon program is located in /usr/local/bin/xdm. This program can be run at any time as root and it will start managing the X display on the local machine. If XDM is to be run every time the machine boots up, a convenient way to do this is by adding an entry to /etc/ttys. For more information about the format and usage of this file, see 節 25.3.2.1, “Adding an Entry to /etc/ttys. There is a line in the default /etc/ttys file for running the XDM daemon on a virtual terminal:

ttyv8   "/usr/local/bin/xdm -nodaemon"  xterm   off secure

By default this entry is disabled; in order to enable it change field 5 from off to on and restart init(8) using the directions in 節 25.3.2.2, “Force init to Reread /etc/ttys. The first field, the name of the terminal this program will manage, is ttyv8. This means that XDM will start running on the 9th virtual terminal.

5.6.3. Configuring XDM

The XDM configuration directory is located in /usr/local/lib/X11/xdm. In this directory there are several files used to change the behavior and appearance of XDM. Typically these files will be found:

FileDescription
XaccessClient authorization ruleset.
XresourcesDefault X resource values.
XserversList of remote and local displays to manage.
XsessionDefault session script for logins.
Xsetup_*Script to launch applications before the login interface.
xdm-configGlobal configuration for all displays running on this machine.
xdm-errorsErrors generated by the server program.
xdm-pidThe process ID of the currently running XDM.

Also in this directory are a few scripts and programs used to set up the desktop when XDM is running. The purpose of each of these files will be briefly described. The exact syntax and usage of all of these files is described in xdm(1).

The default configuration is a simple rectangular login window with the hostname of the machine displayed at the top in a large font and Login: and Password: prompts below. This is a good starting point for changing the look and feel of XDM screens.

5.6.3.1. Xaccess

The protocol for connecting to XDM-controlled displays is called the X Display Manager Connection Protocol (XDMCP). This file is a ruleset for controlling XDMCP connections from remote machines. It is ignored unless the xdm-config is changed to listen for remote connections. By default, it does not allow any clients to connect.

5.6.3.2. Xresources

This is an application-defaults file for the display chooser and login screens. In it, the appearance of the login program can be modified. The format is identical to the app-defaults file described in the X11 documentation.

5.6.3.3. Xservers

This is a list of the remote displays the chooser should provide as choices.

5.6.3.4. Xsession

This is the default session script for XDM to run after a user has logged in. Normally each user will have a customized session script in ~/.xsession that overrides this script.

5.6.3.5. Xsetup_*

These will be run automatically before displaying the chooser or login interfaces. There is a script for each display being used, named Xsetup_ followed by the local display number (for instance Xsetup_0). Typically these scripts will run one or two programs in the background such as xconsole.

5.6.3.6. xdm-config

This contains settings in the form of app-defaults that are applicable to every display that this installation manages.

5.6.3.7. xdm-errors

This contains the output of the X servers that XDM is trying to run. If a display that XDM is trying to start hangs for some reason, this is a good place to look for error messages. These messages are also written to the user's ~/.xsession-errors file on a per-session basis.

5.6.4. Running a Network Display Server

In order for other clients to connect to the display server, you must edit the access control rules, and enable the connection listener. By default these are set to conservative values. To make XDM listen for connections, first comment out a line in the xdm-config file:

! SECURITY: do not listen for XDMCP or Chooser requests
! Comment out this line if you want to manage X terminals with xdm
DisplayManager.requestPort:     0

and then restart XDM. Remember that comments in app-defaults files begin with a ! character, not the usual #. More strict access controls may be desired —— look at the example entries in Xaccess, and refer to the xdm(1) manual page for further infomation.

5.6.5. Replacements for XDM

Several replacements for the default XDM program exist. One of them, kdm (bundled with KDE) is described later in this chapter. The kdm display manager offers many visual improvements and cosmetic frills, as well as the functionality to allow users to choose their window manager of choice at login time.

5.7. 桌面環境

Contributed by Valentino Vaschetto.

本章會介紹在 FreeBSD 中的 X 裡頭,有哪些不同的桌面環境。 桌面環境範圍很廣,從簡單的 window manager 到 完整的桌面應用程式,例如 KDEGNOME

5.7.1. GNOME

5.7.1.1. 關於 GNOME

GNOME is a user-friendly desktop environment that enables users to easily use and configure their computers. GNOME includes a panel (for starting applications and displaying status), a desktop (where data and applications can be placed), a set of standard desktop tools and applications, and a set of conventions that make it easy for applications to cooperate and be consistent with each other. Users of other operating systems or environments should feel right at home using the powerful graphics-driven environment that GNOME provides. More information regarding GNOME on FreeBSD can be found on the FreeBSD GNOME Project's web site. The web site also contains fairly comprehensive FAQs about installing, configuring, and managing GNOME.

5.7.1.2. Installing GNOME

可透過 package 或 Ports Collection 的方式來輕鬆安裝:

透過網路利用 package 安裝 GNOME

# pkg_add -r gnome2

從 ports tree 透過原始碼編譯安裝 GNOME

# cd /usr/ports/x11/gnome2
# make install clean

GNOME 安裝完成後, 必須告訴 X server 啟動 GNOME 而非原本的 window manager。

啟動 GNOME 最簡單的方法是利 用 GDM(GNOME Display Manager)。 GDM, which is installed as a part of the GNOME desktop (but is disabled by default), can be enabled by adding gdm_enable="YES" to /etc/rc.conf. Once you have rebooted, GNOME will start automatically once you log in —— no further configuration is necessary.

GNOME may also be started from the command-line by properly configuring a file named .xinitrc. If a custom .xinitrc is already in place, simply replace the line that starts the current window manager with one that starts /usr/local/bin/gnome-session instead. If nothing special has been done to the configuration file, then it is enough simply to type:

% echo "/usr/local/bin/gnome-session" > ~/.xinitrc

Next, type startx, and the GNOME desktop environment will be started.

注意:

If an older display manager, like XDM, is being used, this will not work. Instead, create an executable .xsession file with the same command in it. To do this, edit the file and replace the existing window manager command with /usr/local/bin/gnome-session:

% echo "#!/bin/sh" > ~/.xsession
% echo "/usr/local/bin/gnome-session" >> ~/.xsession
% chmod +x ~/.xsession

Yet another option is to configure the display manager to allow choosing the window manager at login time; the section on KDE details explains how to do this for kdm, the display manager of KDE.

5.7.1.3. Anti-aliased Fonts with GNOME

X11 supports anti-aliasing via its RENDER extension. GTK+ 2.0 and greater (the toolkit used by GNOME) can make use of this functionality. Configuring anti-aliasing is described in 節 5.5.3, “Anti-Aliased 規格的字型”. So, with up-to-date software, anti-aliasing is possible within the GNOME desktop. Just go to ApplicationsDesktop PreferencesFont, and select either Best shapes, Best contrast, or Subpixel smoothing (LCDs). For a GTK+ application that is not part of the GNOME desktop, set the environment variable GDK_USE_XFT to 1 before launching the program.

5.7.2. KDE

5.7.2.1. About KDE

KDE is an easy to use contemporary desktop environment. Some of the things that KDE brings to the user are:

  • A beautiful contemporary desktop

  • A desktop exhibiting complete network transparency

  • An integrated help system allowing for convenient, consistent access to help on the use of the KDE desktop and its applications

  • Consistent look and feel of all KDE applications

  • Standardized menu and toolbars, keybindings, color-schemes, etc.

  • Internationalization: KDE is available in more than 40 languages

  • Centralized, consistent, dialog-driven desktop configuration

  • A great number of useful KDE applications

KDE comes with a web browser called Konqueror, which is a solid competitor to other existing web browsers on UNIX® systems. More information on KDE can be found on the KDE website. For FreeBSD specific information and resources on KDE, consult the KDE on FreeBSD team's website.

5.7.2.2. 安裝 KDE

如同 GNOME 或其他桌面管理軟體一樣, 也可以輕鬆透過 package 或 Ports Collection 來安裝:

To install the KDE package from the network, simply type:

# pkg_add -r kde

pkg_add(1) will automatically fetch the latest version of the application.

To build KDE from source, use the ports tree:

# cd /usr/ports/x11/kde3
# make install clean

After KDE has been installed, the X server must be told to launch this application instead of the default window manager. This is accomplished by editing the .xinitrc file:

% echo "exec startkde" > ~/.xinitrc

Now, whenever the X Window System is invoked with startx, KDE will be the desktop.

If a display manager such as XDM is being used, the configuration is slightly different. Edit the .xsession file instead. Instructions for kdm are described later in this chapter.

5.7.3. More Details on KDE

Now that KDE is installed on the system, most things can be discovered through the help pages, or just by pointing and clicking at various menus. Windows® or Mac® users will feel quite at home.

The best reference for KDE is the on-line documentation. KDE comes with its own web browser, Konqueror, dozens of useful applications, and extensive documentation. The remainder of this section discusses the technical items that are difficult to learn by random exploration.

5.7.3.1. The KDE Display Manager

An administrator of a multi-user system may wish to have a graphical login screen to welcome users. XDM can be used, as described earlier. However, KDE includes an alternative, kdm, which is designed to look more attractive and include more login-time options. In particular, users can easily choose (via a menu) which desktop environment (KDE, GNOME, or something else) to run after logging on.

To enable kdm, the ttyv8 entry in /etc/ttys has to be adapted. The line should look as follows:

ttyv8 "/usr/local/bin/kdm -nodaemon" xterm on secure

5.7.4. XFce

5.7.4.1. About XFce

XFce is a desktop environment based on the GTK+ toolkit used by GNOME, but is much more lightweight and meant for those who want a simple, efficient desktop which is nevertheless easy to use and configure. Visually, it looks very much like CDE, found on commercial UNIX® systems. Some of XFce's features are:

  • A simple, easy-to-handle desktop

  • Fully configurable via mouse, with drag and drop, etc.

  • Main panel similar to CDE, with menus, applets and applications launchers

  • Integrated window manager, file manager, sound manager, GNOME compliance module, and more

  • Themeable (since it uses GTK+)

  • Fast, light and efficient: ideal for older/slower machines or machines with memory limitations

More information on XFce can be found on the XFce website.

5.7.4.2. Installing XFce

A binary package for XFce exists (at the time of writing). To install, simply type:

# pkg_add -r xfce4

Alternatively, to build from source, use the ports collection:

# cd /usr/ports/x11-wm/xfce4
# make install clean

Now, tell the X server to launch XFce the next time X is started. Simply type this:

% echo "/usr/local/bin/startxfce4" > ~/.xinitrc

The next time X is started, XFce will be the desktop. As before, if a display manager like XDM is being used, create an .xsession, as described in the section on GNOME, but with the /usr/local/bin/startxfce4 command; or, configure the display manager to allow choosing a desktop at login time, as explained in the section on kdm.

部 II. 一般性工作

既然基礎的部分已經提過了,接下來的這個部分將會討論一些常會用到的 FreeBSD 的特色,這些章節包括:

  • 介紹給您常見且實用的桌面應用軟體:網頁瀏覽器、生產力工具、文件檢視程式等。

  • 介紹給您眾多 FreeBSD 上可用的多媒體工具。

  • 解釋如何編譯自訂 FreeBSD 核心以增加額外系統功能的流程。

  • 詳細描述列印系統,包含桌上型印表機及網路印表機的設定。

  • 展示給您看如何在您的 FreeBSD 系統中執行 Linux 應用軟體。

這些章節中有些需要您預先閱讀些相關文件,在各章節開頭的概要內會提及。

章 6. 桌面環境應用程式

Contributed by Christophe Juniet.

6.1. 概述

在 FreeBSD 上面可以執行非常多種類的桌面應用程式, 像是網頁瀏覽器和文字處理軟體等。 這些程式大都可以透過套件來安裝或是從 Ports Collection 中自動編譯安裝。 許多新的使用者會希望能在在他們的桌面系統中找到這些程式。 這章將會告訴你如何不用費太多功夫去安裝一些熱門的桌面應用程式, 不管是從套件或是從 Ports Collection 中安裝。

需要注意到的是:當從 ports 中安裝程式的時候, 它們是從原始碼開始編譯的。依照你編譯的 ports 和電腦速度(硬體等級), 有可能會花很長一段時間才能完成。 如果從原始碼編譯對你來說會花太多時間的話, 大部分的 ports 你都能找到事先編譯好的套件來安裝。

因為 FreeBSD 具有相容 Linux 二進制的特性, 許多原先在 Linux 上開發的應用程式都能在你的 FreeBSD 桌面環境執行。 在安裝任何 Linux 應用程式之前,強烈建議你先閱讀 章 10, Linux® 二進位檔的相容性 Linux 執行相容模式這個章節。 而許多用 Linux 二進制相容模式的軟體在 ports 裡頭通常都會用 linux- 開頭。 當你在搜尋某個特定軟體時,記住這點,並且可以使用 whereis(1) 來找。 在下列的說明中, 都假設你在安裝任何 Linux 應用軟體之前, 已經事先啟用了 Linux 二進制相容模式。

下列目錄是這章中所涵蓋的應用程式:

  • 瀏覽器 (像是 Mozilla, Opera, Firefox, Konqueror)

  • 辦公軟體 (像是 KOffice, AbiWord, The GIMP, OpenOffice.org)

  • 文件瀏覽軟體 (像是 Acrobat Reader®, gv, Xpdf, GQview)

  • 財務處理軟體 (像是 GnuCash, Gnumeric, Abacus)

在閱讀這章之前,你必須

要知道更多關於多媒體環境的資訊,請先閱讀 章 7, 多媒體影音娛樂(Multimedia) 多媒體章節。 如果你想要設定和使用電子郵件,也請你先看 章 27, 電子郵件郵件章節。

6.2. 瀏覽器

在 FreeBSD 中並沒有預先安裝好的特定瀏覽器。 但在 Ports Collection 之中卻有許多瀏覽器可供你安裝使用。 如果你沒有足夠時間去編譯所有的東西 (在某些情況下這可能會花上很長的一段時間), 這些都有現成的套件可供直接安裝。

KDEGNOME 桌面環境都已提供 HTML 瀏覽器。 請參考 節 5.7, “桌面環境” 來了解更多有關如何設定這些完整的桌面環境系統資訊。

如果你在尋找輕量化的瀏覽器,你可以從 Ports Collection 中找到下面的幾種: www/dillo, www/links, 或 www/w3m

這節介紹這些瀏覽器:

瀏覽器名稱所需的系統資源從 ports 安裝時間主要相依的軟體
MozillaGtk+
OperaFreeBSD 和 Linux 的版本都有。 Linux 的版本需要 Linux 二進制相容模組以及 linux-openmotif.
Firefox中度Gtk+
Konqueror中度KDE 函式庫

6.2.1. Mozilla

Mozilla 是相當現代化、穩定且完全移植至 FreeBSD 系統上。 它也具備有十分符合 HTML 標準的顯示引擎, 它更提供了郵件及新聞群組的閱讀功能。 此外如果你打算要自己寫一些網頁的話,它還提供了 HTML 的編輯器。 如果是 Netscape® 的使用者, 你可能會認出這跟 Communicator 很像, 它們其實同樣是使用相同基礎的瀏覽器。

在速度較慢,像是 CPU 速度少於 233MHz 或是小於 64MB 記憶體的機器上面, 完全使用 Mozilla 會是件極度耗費資源的事。 所以在這樣的機器上面,你可能會想要使用 Opera 這樣輕量級的瀏覽器,而接下來後面會提到。

如果你有什麼原因不能或是不想編譯 Mozilla 的話,FreeBSD GNOME 團隊已經為你做好了這件事。 只要用下面的指令透過網路安裝套件就行了:

# pkg_add -r mozilla

如果沒有找到套件可以使用,而你也有足夠的時間和磁碟空間來編譯 Mozilla 並安裝到你的系統中, 你可以透過下列步驟來安裝:

# cd /usr/ports/www/mozilla
# make install clean

Mozilla 需要使用 root 的權限來執行 chrome 註冊來確保正確的初始化。 另外,如果你需要抓一些額外的外掛程式像是 mouse gestures, 你就必須要使用 root 的權限來安裝, 以適當的安裝這些外掛程式。

一旦你完成了 Mozilla 的安裝,你就再也不需要 root 的權限了。  你可以直接打下面的指令來啟動 Mozilla

% mozilla

也可以直接打下列指令,直接啟動郵件和新聞閱讀器:

% mozilla -mail

6.2.2. Firefox

Firefox 是以 Mozilla 原始碼為基礎的新世代瀏覽器。 Mozilla 是一堆應用軟體的整合套裝, 像是瀏覽器、郵件程式、聊天室軟體等所組成。 Firefox 則純粹是瀏覽器, 這也是為何它能短小精悍之故。

可以打下列指令來安裝:

#pkg_add -r firefox

也可以透過 Ports Collection,以編譯原始碼的方式來安裝:

#cd /usr/ports/www/firefox
# make install clean

6.2.3. Firefox, Mozilla 的 Java™ plugin 程式

注意:

本節以及下一節,均假設您已裝好 FirefoxMozilla

FreeBSD 基金會與 Sun Microsystems 有達成授權協議, 可以散播 Java Runtime Environment(JRE™) 及 Java Developement Kit(JDK™) 的 FreeBSD 版 binary(執行檔)。 FreeBSD 版的 binary 可以在 FreeBSD 基金會 網站下載。

要讓 FirefoxMozilla 支援 Java™ 的話,首先要先裝 java/javavmwrapper 這個 port。 然後再去 http://www.freebsdfoundation.org/downloads/java.shtml 下載 Diablo JRE,並以 pkg_add(1) 指令來安裝之。

接著啟動瀏覽器,在網址列輸入 about:plugins 然後按 Enter 鍵,就會顯示目前已裝的 plugins 清單, 這時應該就可以看到 Java 也有列出來。 若仍未看到的話,那就切換為 root 帳號, 打下列指令:

# ln -s /usr/local/diablo-jre1.5.0/plugin/i386/ns7/libjavaplugin_oji.so \
  /usr/local/lib/browser_plugins/

最後,重啟瀏覽器即可。

6.2.4. Firefox, Mozilla 的 Macromedia® Flash™ plugin 程式

Macromedia® Flash™ plugin 程式並沒有 FreeBSD 版, 然而可以透過軟體層(wrapper)來執行 Linux 版的 plugin 程式。 這個 wrapper 同時也支援 Adobe® Acrobat® 以及 RealPlayer® plugin 等。

接下來去裝 www/linuxpluginwrapper。 linuxpluginwrapper 需要先裝一個很大的 emulators/linux_baseport。 然後根據 port 所指示的作法, 去正確地設定你的 /etc/libmap.conf! 設定的範例檔案位於 /usr/local/share/examples/linuxpluginwrapper/ 的目錄底下。

下一步,則是裝 www/linux-flashplugin7。 裝好後,再啟動瀏覽器,在網址列輸入 about:plugins, 然後按 Enter 鍵就會顯示目前已裝的 plugin 清單。

Flash™ plugin 沒出現的話,大多可能是因為漏了做 symlink 連結之故。 請切為 root 帳號,打下列指令:

# ln -s /usr/local/lib/npapi/linux-flashplugin/libflashplayer.so \
  /usr/local/lib/browser_plugins/
# ln -s /usr/local/lib/npapi/linux-flashplugin/flashplayer.xpt \
  /usr/local/lib/browser_plugins/

最後,重啟瀏覽器應該就可看到了。

注意:

linuxpluginwrapper 只能在 i386™ 的系統架構下運行。

6.2.5. Opera

Opera 是個具備完整功能、符合標準的瀏覽器。 它同時也具備了內建的郵件、新聞閱讀器、IRC、RSS/Atom feeds 閱讀器等。 此外 Opera 更是個輕量級、 執行速度又快的瀏覽器。 它在 ports 中有兩種版本:「原生」的 FreeBSD 版本還有在 Linux 模擬模式下的版本。

要用 Opera 的 FreeBSD 版本來瀏覽網頁的話, 用下面的指令安裝:

# pkg_add -r opera

有些 FTP 站台並沒有全部的套件, 但是打下面的指令就能從 Ports Collection 中安裝:

# cd /usr/ports/www/opera
# make install clean

要安裝 Opera 的 Linux 版本的話, 請將上面例子中的 opera 替換成 linux-opera。 有些時候, Linux 的版本是十分有用的, 像是只有 Linux 版本外掛程式的時候。 但在其他方面來說, FreeBSD 和 Linux 的版本功能上是一樣的。

6.2.6. Konqueror

KonquerorKDE 桌面系統的一部分,但是它也可以藉由安裝 x11/kdebase3 在 KDE 環境以外使用。 Konqueror 不只是個網頁瀏覽器, 他同時也是檔案管理器和多媒體瀏覽器。

Konqueror 也有許多的外掛程式, 這些外掛程式可以從 misc/konq-plugins 中安裝。

Konqueror 也支援 Flash 的外掛程式。 如何安裝的說明請參閱:http://freebsd.kde.org/howto.php

6.3. 辦公室軟體

當開始進行辦公, 新的使用者通常會去找好用的辦公室軟體或是好上手的文字處理器。 目前 有些桌面環境 像是 KDE已經提供了辦公軟體組合的套件。 FreeBSD 提供了所需的所有辦公軟體,桌面環境也不例外。

這節涵蓋了下列的這些軟體:

軟體名稱所需系統資源從 Ports 安裝的時間主要相依套件
KOfficeKDE
AbiWordGtk+ 或是 GNOME
The GimpGtk+
OpenOffice.org很久JDK™ 1.4, Mozilla

6.3.1. KOffice

KDE 社群在它的桌面環境裡頭提供了一個可以在 KDE 外使用的辦公軟體組合。 它包含了四種模組: KWord 是文字處理器, KSpread 是試算表程式, KPresenter 是簡報播放程式, 另外 Karbon14 讓你可以產生圖形化的文件。 [5]

在安裝最新版的 KOffice 之前, 請先確定你有最新版本的 KDE

若要用套件來安裝 KOffice, 請依照下面的指令:

# pkg_add -r koffice

如果套件不存在的話,你可以使用 ports collection. 例如要安裝 KDE3 中的 KOffice,請使用下列指令安裝:

# cd /usr/ports/editors/koffice-kde3
# make install clean

6.3.2. AbiWord

AbiWord 是一個免費的文字處理軟體,外觀和感覺都近似於 Microsoft® Word。 它適合處理文件、信件、報告、備忘錄等等。 它也非常快速,包含了許多功能而且非常容易上手。

AbiWord 可以輸入或輸出許多檔案格式, 包括一些有專利的格式,例如微軟(Microsoft)公司的 .doc 格式。

AbiWord 也能用套件安裝, 你可以用下列指令來安裝:

# pkg_add -r abiword

如果找不到套件的話,它也可以從 Ports Collection 中編譯安裝。 而 Ports Collection 應該要保持在最新的狀態。 AbiWord 可以透過下列方式編譯安裝:

# cd /usr/ports/editors/abiword
# make install clean

6.3.3. The GIMP

對於影像的編輯及修改來說,GIMP 是非常精緻的影像處理軟體。 它可以當作簡單的繪圖軟體或是高品質的相片處理軟體。 它支援為數眾多的外掛程式及指令稿 (script-fu) 介面。 GIMP 可以讀寫許多檔案格式。 它也支援掃描器 [6] 和手寫板。

譯註:GIMP 在目前是 2.x 版,如果你想要安裝 1.x 版的話,請用 Ports Collection 中的 graphics/gimp1。 另外如果你已經使用習慣 Adobe Photoshop,而且不習慣 GIMP 介面的話,你也可以嘗試安裝 graphics/gimpshop, 它的使用介面十分類似 Adobe Photoshop。

你可以使用下面指令安裝套件:

# pkg_add -r gimp

如果的你的 FTP 站台沒有這個套件,你可以使用 Ports Collection。 在 Ports Collection 的 graphics 目錄下也包含了 The Gimp Manual(GIMP 使用手冊)。 下面示範如何安裝這些程式:

# cd /usr/ports/graphics/gimp
# make install clean
# cd /usr/ports/graphics/gimp-manual-pdf
# make install clean

譯註:另外在 Ports Collection 中也有一些外掛程式可以使用, 例如說可以處理數位相機 raw 檔案格式的 gimp-ufraw

注意:

GIMP 使用手冊也有 HTML 格式的,你可以在 graphics/gimp-manual-html 中安裝。

6.3.4. OpenOffice.org

OpenOffice.org 包含了所有完整的辦公軟體組合: 文字處理器、試算表、簡報軟體還有繪圖軟體。 除了它的使用者介面非常類似其他的辦公軟體, 他還能夠輸入和輸出許多熱門的檔案格式。 它也包含了不同語言的使用者介面、拼字檢查和字典。

OpenOffice.org 的文字處理器使用 XML 檔案格式來增加移植性及彈性。 試算表程式支援巨集(macro)功能而且能夠使用外來的資料庫介面。 OpenOffice.org 已經十分穩定, 並且能夠在 Windows®, Solaris™, Linux, FreeBSD 及 Mac OS® X 等作業系統上面執行。 想知道更多關於 OpenOffice.org 的資訊可以在 OpenOffice.org 網頁 上查詢。你也可以在 FreeBSD OpenOffice.org 移植團隊 的網頁上查詢關於 FreeBSD 上 OpenOffice 特定的資訊或直接下載已編譯好的套件

要安裝 OpenOffice.org, 請用以下方式來執行:

# pkg_add -r openoffice.org

注意:

當你在使用 FreeBSD -RELEASE 版本的時候,上面的作法應該行得通。 要是其他的版本,你應該看一下 FreeBSD OpenOffice.org 移植團隊的網站,並且用 pkg_add(1) 安裝合適的套件。 在這個站台都可以下載到穩定的釋出版(release)或開發中的版本。

當已經安裝完之後,你只要鍵入下面的指令就能執行 OpenOffice.org

% openoffice.org

譯註:端看你的版本,有時候需要輸入如 openoffice.org-2.0.1 之類的指令,不過你也可以用 shell 中的 alias 或是用 symbolic link 來處理。

注意:

在第一次啟動的時候,OpenOffice 會問到一些問題。 而且在你的家目錄底下會自動建立 .openoffice.org2 的資料夾。

如果無法取得 OpenOffice.org 的套件,你仍然可以選擇從 port 編譯。 不過你必須謹記在心:編譯的過程會需要大量的磁碟空間且相當耗時。

# cd /usr/ports/editors/openoffice.org-2
# make install clean

注意:

如果你想要安裝本地化的版本,把前面的指令代換成下面的:

# make LOCALIZED_LANG=你的語言 install clean

你必須把你的語言 換成正確的語言 ISO-code [7] 所支援的語言代碼清單可以在 port 目錄裡的 files/Makefile.localized 檔案中找到。

一旦完成了上述步驟, OpenOffice.org 可用以下指令啟動:

% openoffice.org

6.4. 文件閱覽器

近年來有些文件格式變得愈來愈流行, 基本的系統中也許不會有這些格式所需的標準閱覽器。 在這一節,我們來看看怎麼安裝這些軟體。

這張涵蓋了下列的軟體

軟體名稱所需系統資源從 Ports 安裝時間主要相依套件
Acrobat Reader®Linux 二進制相容模組
gvXaw3d
XpdfFreeType
GQviewGtk+ 或是 GNOME

6.4.1. Acrobat Reader®

許多文件在散佈的時候都是用 PDF 的檔案格式, 這個格式是基於 可攜式文件格式(Portable Document Format)。 其中一個推薦的閱覽軟體就是Acrobat Reader®, 它是由 Adobe 公司發行給 Linux 使用的版本。 因為 FreeBSD 也可以執行 Linux 二進位檔案, 所以它也能在 FreeBSD 上面執行。

要從 Ports Collection 中安裝 Acrobat Reader® 7 只要:

# cd /usr/ports/print/acroread7
# make install clean

因為授權的限制,所以不提供編譯好的套件。

6.4.2. gv

gvPostScript® 和 PDF 的閱覽器。 它建構於 ghostview的基礎上, 不過因為使用 Xaw3d 函式庫, 所以外觀看起來比較漂亮。 gv 速度快,介面簡潔並且有許多功能, 比如說方向性、紙張大小、縮放比例、和反鋸齒(antialias)等。 而且幾乎所有的使用都可以從鍵盤或滑鼠來完成。

用套件來安裝 gv,使用下列指令:

# pkg_add -r gv

如果你不能取得套件,你可以使用 Ports Collection:

# cd /usr/ports/print/gv
# make install clean

6.4.3. Xpdf

如果你想要一個小型的 FreeBSD PDF 閱覽軟體, Xpdf是個輕量級而且有效率的閱覽器。 它只需要非常少的資源而且十分穩定。 它只使用標準的 X 字型而不需要 Motif® 或是其他的 X 工具組(toolkit)。

用套件來安裝 Xpdf,使用下列指令:

# pkg_add -r xpdf

如果套件不存在或是你偏好使用 Ports Collection, 使用以下指令:

# cd /usr/ports/graphics/xpdf
# make install clean

一旦完成了安裝,你可以啟動 Xpdf 並且使用滑鼠右鍵去使用選單。

6.4.4. GQview

GQview 是影像管理軟體。 你可以用單鍵來閱覽檔案、啟動額外的編輯器、縮圖預覽等功能。 它也有幻燈片播放(slideshow)及一些基本的檔案操作功能。 你可用 GQview 管理影像集並能輕鬆地找出重複的檔案。 GQview 能夠使用全螢幕觀看並支援國際化。

如果你想要安裝 GQview的套件, 請使用下列指令:

# pkg_add -r gqview

如果套件無法取得,或是你比較喜歡使用 Ports Collection,只要:

# cd /usr/ports/graphics/gqview
# make install clean

6.5. 財務

如果有任何理由你想要在你的 FreeBSD 桌面環境上管理你的個人財務, 這裡有一些功能強大、使用簡單的應用程式可供安裝。 這些財務管理軟體之中有些是相容於流行的 QuickenExcel 文件。

這節涵蓋了下面這些軟體:

軟體名稱所需系統資源從 Ports 安裝的時間主要的相依套件
GnuCashGNOME
GnumericGNOME
AbacusTcl/Tk

6.5.1. GnuCash

GnuCashGNOME 團隊努力成果中的一部分, 而 GNOME 主要是提供終端使用者(end-users) 親切而強大的桌面應用程式。 使用 GnuCash, 你可以持續紀錄你的收入及花費、你的銀行帳戶、或是你的股票證券等。 它的特性是介面直覺但功能仍非常專業。

GnuCash 提供了一個智慧的註冊器、 帳戶層級系統、許多快速鍵及自動完成(auto-completion)模式。 它也能分開單一的報表至數個詳細的部份。 GnuCash 也能夠輸入及合併 Quicken QIF 檔案。 它也能處理大部分國際的日期及通用貨幣之格式。

要安裝 GnuCash 到你的系統中, 只要做下列步驟:

# pkg_add -r gnucash

如果不能取得套件,你可以使用 Ports Collection:

# cd /usr/ports/finance/gnucash
# make install clean

6.5.2. Gnumeric

GnumericGNOME 桌面環境中的試算表。 它的特點是能夠根據儲存格格式(cell format)及自動補齊的系統, 來方便自動地「猜出」使用者的輸入。 它也能夠輸入許多熱門的檔案格式,像是 Excel, Lotus 1-2-3, 或是 Quattro ProGnumeric 支援使用 math/guppi 繪圖軟體來繪圖。 它有許多內建的函數而且允許一般的儲存格格式,像是: 數字、貨幣、日期、時間及其他格式等。

要用套件安裝 Gnumeric,只要打以下指令:

# pkg_add -r gnumeric

如果套件不存在,你可以做下面的步驟來使用 Ports Collection 編譯安裝:

# cd /usr/ports/math/gnumeric
# make install clean

6.5.3. Abacus

Abacus 是個小巧又使用簡單的試算表。 它包含了許多內建的函數,在相關的領域如統計學、財務、數學中很實用。 它也可以輸出輸入 Excel 的檔案格式。 另外 Abacus也能夠輸出 PostScript® 格式。

從套件安裝 Abacus 只要做:

# pkg_add -r abacus

如果套件不能取得的話,你可以使用 Ports Collection, 並用以下指令:

# cd /usr/ports/deskutils/abacus
# make install clean

6.6. 摘要

雖然 FreeBSD 是因為效能及穩定性而在 ISP 之間很流行, 不過它也可以完全當作桌面環境(desktop)來使用, 並不侷限於使用在伺服器上面。目前有數千種應用程式的 套件(packages)ports, 可供使用,你可以根據你的需求打造出一個完美的桌面環境。

下面是這章涵蓋的所有桌面應用軟體之快速回顧表:

軟體名稱套件名稱Ports 名稱
Mozillamozillawww/mozilla
Operaoperawww/opera
Firefoxfirefoxwww/firefox
KOfficekoffice-kde3editors/koffice-kde3
AbiWordabiwordeditors/abiword
The GIMPgimpgraphics/gimp
OpenOffice.orgopenofficeeditors/openoffice-1.1
Acrobat Reader®acroreadprint/acroread7
gvgvprint/gv
Xpdfxpdfgraphics/xpdf
GQviewgqviewgraphics/gqview
GnuCashgnucashfinance/gnucash
Gnumericgnumericmath/gnumeric
Abacusabacusdeskutils/abacus


[5] 譯註:Karbon14 是向量繪圖軟體,以前叫 Kontour,更早之前稱為 Killustrator。

[6] 譯註:你必須透過 sane-frontends 或 xsane 來掃描

[7] 譯註:臺灣正體中文使用者為 zh-TW。

章 7. 多媒體影音娛樂(Multimedia)

Edited by Ross Lippert.

7.1. 概述

FreeBSD 廣泛地支援各種音效卡, 讓您可以享受來自電腦上的高傳真音質(Hi-Fi), 此外還包括了錄製和播放 MPEG Audio Layer 3 (MP3)、 WAV、 以及 Ogg Vorbis 等許多種格式聲音的能力。同時 FreeBSD Ports Collection 也包括了許多的應用程式, 讓您可以錄音、編修音效以及控制 MIDI 配備。

要是喜歡動手嘗試不同的體驗, FreeBSD 也能播放一般的視訊檔和 DVD。 編碼、轉換和播放視訊的程式比起處理聲音的程式略少一些。例如, 在撰寫這章時, FreeBSD Ports Collection 中還沒有類似 audio/sox 那樣好用的編碼工具,能夠用來轉換不同的格式。 不過,這個領域的軟體研發進展是相當迅速的。

本章將介紹設定音效卡的必要步驟。先前介紹到的 X11 (章 5, X Window 視窗系統) 安裝和設定裡,已經講到了顯示卡的部份, 但要想有更好的播放效果, 仍需要一些細部調整。

讀完這章,您將了解:

  • 如何設定系統,以正確識別音效卡。

  • 如何運用樣本程式,以測試音效卡是否正常運作。

  • 如何解決音效卡的設定問題。

  • 如何播放、錄製 MP3 及其他聲音檔案格式。

  • X server 是如何支援顯示卡。

  • Ports Collections 內有哪些好用的影像播放、錄製軟體。

  • 如何播放 DVD 的 .mpg.avi

  • 如何從 CD 和 DVD 中擷取(rip)檔案。

  • 如何設定電視卡

  • 如何設定掃描器

在閱讀這章之前,您應當了解:

警告:

如果要用 mount(8) 指令來 mount 音樂光碟的話,通常會發生錯誤, 甚至導致 kernel panic。 這是因為音樂光碟是特殊編碼,而非一般的 ISO 檔案系統之故。

7.2. 設定音效卡

Contributed by Moses Moore.
加強 FreeBSD 5.X 的內容:Marc Fonvieille.

7.2.1. 設定系統

開始設定之前,必須先知道你的音效卡型號、晶片為何,以及是 PCI 或 ISA 規格。 FreeBSD 有支援許多種的 PCI、ISA 音效卡,請檢查支援的音效硬體表 Hardware Notes,以確認你的音效卡是否支援。 本文也會提到相對應該卡的驅動程式。

要使用音效卡,必須要載入正確的驅動程式才行。有兩種方式都可以完成這動作, 最簡單方式就是以 kldload(8) 來輕鬆載入 kernel 動態模組(module), 像是下列指令:

# kldload snd_emu10k1

或者把相關驅動程式加到 /boot/loader.conf 檔,像是:

snd_emu10k1_load="YES"

上面例子是給 Creative SoundBlaster® Live! 音效卡使用的。 其他可用的音效卡驅動程式模組,可參考 /boot/defaults/loader.conf 範例。 若不確定到底該用哪一種驅動程式,那麼可以試試載入 snd_driver 模組看看:

# kldload snd_driver

This is a metadriver loading the most common device drivers at once. This speeds up the search for the correct driver. It is also possible to load all sound drivers via the /boot/loader.conf facility.

If you wish to find out the driver selected for your soundcard after loading the snd_driver metadriver, you may check the /dev/sndstat file with the cat /dev/sndstat command.

注意:

Under FreeBSD 4.X, to load all sound drivers, you have to load the snd module instead of snd_driver.

A second method is to statically compile in support for your sound card in your kernel. The section below provides the information you need to add support for your hardware in this manner. For more information about recompiling your kernel, please see 章 8, 設定 FreeBSD Kernel.

7.2.1.1. Configuring a Custom Kernel with Sound Support

The first thing to do is adding the generic audio driver sound(4) to the kernel, for that you will need to add the following line to the kernel configuration file:

device sound

Under FreeBSD 4.X, you would use the following line:

device pcm

Then we have to add the support for our sound card. Therefore, we need to know which driver supports the card. Check the supported audio devices list of the Hardware Notes, to determine the correct driver for your sound card. For example, a Creative SoundBlaster® Live! sound card is supported by the snd_emu10k1(4) driver. To add the support for this card, use the following:

device snd_emu10k1

Be sure to read the manual page of the driver for the syntax to use. Information regarding the syntax of sound drivers in the kernel configuration can also be found in the /usr/src/sys/conf/NOTES file (/usr/src/sys/i386/conf/LINT for FreeBSD 4.X).

Non-PnP ISA cards may require you to provide the kernel with information on the sound card settings (IRQ, I/O port, etc). This is done via the /boot/device.hints file. At system boot, the loader(8) will read this file and pass the settings to the kernel. For example, an old Creative SoundBlaster® 16 ISA non-PnP card will use the snd_sbc(4) driver in conjunction with snd_sb16(4). For this card the following lines have to be added to the kernel configuration file:

device snd_sbc
device snd_sb16

as well as the following in /boot/device.hints:

hint.sbc.0.at="isa"
hint.sbc.0.port="0x220"
hint.sbc.0.irq="5"
hint.sbc.0.drq="1"
hint.sbc.0.flags="0x15"

In this case, the card uses the 0x220 I/O port and the IRQ 5.

The syntax used in the /boot/device.hints file is covered in the sound driver manual page. On FreeBSD 4.X, these settings are directly written in the kernel configuration file. In the case of our ISA card, we would only use this line:

device sbc0 at isa? port 0x220 irq 5 drq 1 flags 0x15

The settings shown above are the defaults. In some cases, you may need to change the IRQ or the other settings to match your card. See the snd_sbc(4) manual page for more information.

注意:

Under FreeBSD 4.X, some systems with built-in motherboard sound devices may require the following option in the kernel configuration:

options PNPBIOS

7.2.2. Testing the Sound Card

After rebooting with the modified kernel, or after loading the required module, the sound card should appear in your system message buffer (dmesg(8)) as something like:

pcm0: <Intel ICH3 (82801CA)> port 0xdc80-0xdcbf,0xd800-0xd8ff irq 5 at device 31.5 on pci0
pcm0: [GIANT-LOCKED]
pcm0: <Cirrus Logic CS4205 AC97 Codec>

The status of the sound card may be checked via the /dev/sndstat file:

# cat /dev/sndstat
FreeBSD Audio Driver (newpcm)
Installed devices:
pcm0: <Intel ICH3 (82801CA)> at io 0xd800, 0xdc80 irq 5 bufsz 16384
kld snd_ich (1p/2r/0v channels duplex default)

The output from your system may vary. If no pcm devices show up, go back and review what was done earlier. Go through your kernel configuration file again and make sure the correct device is chosen. Common problems are listed in 節 7.2.2.1, “Common Problems”.

If all goes well, you should now have a functioning sound card. If your CD-ROM or DVD-ROM drive is properly coupled to your sound card, you can put a CD in the drive and play it with cdcontrol(1):

% cdcontrol -f /dev/acd0 play 1

Various applications, such as audio/workman can provide a friendlier interface. You may want to install an application such as audio/mpg123 to listen to MP3 audio files. A quick way to test the card is sending data to the /dev/dsp, like this:

% cat filename > /dev/dsp

where filename can be any file. This command line should produce some noise, confirming the sound card is actually working.

注意:

FreeBSD 4.X users need to create the sound card device nodes before being able to use it. If the card showed up in message buffer as pcm0, you will have to run the following as root:

# cd /dev
# sh MAKEDEV snd0

If the card detection returned pcm1, follow the same steps as shown above, replacing snd0 with snd1.

MAKEDEV will create a group of device nodes that will be used by the different sound related applications.

Sound card mixer levels can be changed via the mixer(8) command. More details can be found in the mixer(8) manual page.

7.2.2.1. Common Problems

ErrorSolution
unsupported subdevice XX

One or more of the device nodes was not created correctly. Repeat the steps above.

sb_dspwr(XX) timed out

The I/O port is not set correctly.

bad irq XX

The IRQ is set incorrectly. Make sure that the set IRQ and the sound IRQ are the same.

xxx: gus pcm not attached, out of memory

There is not enough available memory to use the device.

xxx: can't open /dev/dsp!

Check with fstat | grep dsp if another application is holding the device open. Noteworthy troublemakers are esound and KDE's sound support.

7.2.3. Utilizing Multiple Sound Sources

Contributed by Munish Chopra.

It is often desirable to have multiple sources of sound that are able to play simultaneously, such as when esound or artsd do not support sharing of the sound device with a certain application.

FreeBSD lets you do this through Virtual Sound Channels, which can be set with the sysctl(8) facility. Virtual channels allow you to multiplex your sound card's playback channels by mixing sound in the kernel.

To set the number of virtual channels, there are two sysctl knobs which, if you are the root user, can be set like this:

# sysctl hw.snd.pcm0.vchans=4
# sysctl hw.snd.maxautovchans=4

The above example allocates four virtual channels, which is a practical number for everyday use. hw.snd.pcm0.vchans is the number of virtual channels pcm0 has, and is configurable once a device has been attached. hw.snd.maxautovchans is the number of virtual channels a new audio device is given when it is attached using kldload(8). Since the pcm module can be loaded independently of the hardware drivers, hw.snd.maxautovchans can store how many virtual channels any devices which are attached later will be given.

注意:

You cannot change the number of virtual channels for a device while it is in use. First close any programs using the device, such as music players or sound daemons.

If you are not using devfs(5), you will have to point your applications at /dev/dsp0.x, where x is 0 to 3 if hw.snd.pcm.0.vchans is set to 4 as in the above example. On a system using devfs(5), the above will automatically be allocated transparently to the user.

7.2.4. 設定預設(Mixer Channel)的音量大小

Contributed by Josef El-Rayes.

注意:

本功能只有在 FreeBSD 5.3-RELEASE 及之後版本才有支援。

The default values for the different mixer channels are hardcoded in the sourcecode of the pcm(4) driver. There are a lot of different applications and daemons that allow you to set values for the mixer they remember and set each time they are started, but this is not a clean solution, we want to have default values at the driver level. This is accomplished by defining the appropriate values in /boot/device.hints. E.g.:

hint.pcm.0.vol="100"

This will set the volume channel to a default value of 100, when the pcm(4) module is loaded.

7.3. MP3 音樂

Contributed by Chern Lee.

MP3 (MPEG Layer 3 Audio) accomplishes near CD-quality sound, leaving no reason to let your FreeBSD workstation fall short of its offerings.

7.3.1. MP3 Players

By far, the most popular X11 MP3 player is XMMS (X Multimedia System). Winamp skins can be used with XMMS since the GUI is almost identical to that of Nullsoft's Winamp. XMMS also has native plug-in support.

XMMS can be installed from the multimedia/xmms port or package.

XMMS' interface is intuitive, with a playlist, graphic equalizer, and more. Those familiar with Winamp will find XMMS simple to use.

The audio/mpg123 port is an alternative, command-line MP3 player.

mpg123 can be run by specifying the sound device and the MP3 file on the command line, as shown below:

# mpg123 -a /dev/dsp1.0 Foobar-GreatestHits.mp3
High Performance MPEG 1.0/2.0/2.5 Audio Player for Layer 1, 2 and 3.
Version 0.59r (1999/Jun/15). Written and copyrights by Michael Hipp.
Uses code from various people. See 'README' for more!
THIS SOFTWARE COMES WITH ABSOLUTELY NO WARRANTY! USE AT YOUR OWN RISK!





Playing MPEG stream from Foobar-GreatestHits.mp3 ...
MPEG 1.0 layer III, 128 kbit/s, 44100 Hz joint-stereo

/dev/dsp1.0 should be replaced with the dsp device entry on your system.

7.3.2. Ripping CD Audio Tracks

Before encoding a CD or CD track to MP3, the audio data on the CD must be ripped onto the hard drive. This is done by copying the raw CDDA (CD Digital Audio) data to WAV files.

The cdda2wav tool, which is a part of the sysutils/cdrtools suite, is used for ripping audio information from CDs and the information associated with them.

With the audio CD in the drive, the following command can be issued (as root) to rip an entire CD into individual (per track) WAV files:

# cdda2wav -D 0,1,0 -B

cdda2wav will support ATAPI (IDE) CDROM drives. To rip from an IDE drive, specify the device name in place of the SCSI unit numbers. For example, to rip track 7 from an IDE drive:

# cdda2wav -D /dev/acd0a -t 7

The -D 0,1,0 indicates the SCSI device 0,1,0, which corresponds to the output of cdrecord -scanbus.

To rip individual tracks, make use of the -t option as shown:

# cdda2wav -D 0,1,0 -t 7

This example rips track seven of the audio CDROM. To rip a range of tracks, for example, track one to seven, specify a range:

# cdda2wav -D 0,1,0 -t 1+7

The utility dd(1) can also be used to extract audio tracks on ATAPI drives, read 節 17.6.5, “Duplicating Audio CDs” for more information on that possibility.

7.3.3. Encoding MP3s

Nowadays, the mp3 encoder of choice is lame. Lame can be found at audio/lame in the ports tree.

Using the ripped WAV files, the following command will convert audio01.wav to audio01.mp3:

# lame -h -b 128 \
--tt "Foo Song Title" \
--ta "FooBar Artist" \
--tl "FooBar Album" \
--ty "2001" \
--tc "Ripped and encoded by Foo" \
--tg "Genre" \
audio01.wav audio01.mp3

128 kbits seems to be the standard MP3 bitrate in use. Many enjoy the higher quality 160, or 192. The higher the bitrate, the more disk space the resulting MP3 will consume--but the quality will be higher. The -h option turns on the higher quality but a little slower mode. The options beginning with --t indicate ID3 tags, which usually contain song information, to be embedded within the MP3 file. Additional encoding options can be found by consulting the lame man page.

7.3.4. Decoding MP3s

In order to burn an audio CD from MP3s, they must be converted to a non-compressed WAV format. Both XMMS and mpg123 support the output of MP3 to an uncompressed file format.

Writing to Disk in XMMS:

  1. Launch XMMS.

  2. Right-click on the window to bring up the XMMS menu.

  3. Select Preference under Options.

  4. Change the Output Plugin to Disk Writer Plugin.

  5. Press Configure.

  6. Enter (or choose browse) a directory to write the uncompressed files to.

  7. Load the MP3 file into XMMS as usual, with volume at 100% and EQ settings turned off.

  8. Press Play —— XMMS will appear as if it is playing the MP3, but no music will be heard. It is actually playing the MP3 to a file.

  9. Be sure to set the default Output Plugin back to what it was before in order to listen to MP3s again.

Writing to stdout in mpg123:

  • Run mpg123 -s audio01.mp3 > audio01.pcm

XMMS writes a file in the WAV format, while mpg123 converts the MP3 into raw PCM audio data. Both of these formats can be used with cdrecord to create audio CDs. You have to use raw PCM with burncd(8). If you use WAV files, you will notice a small tick sound at the beginning of each track, this sound is the header of the WAV file. You can simply remove the header of a WAV file with the utility SoX (it can be installed from the audio/sox port or package):

% sox -t wav -r 44100 -s -w -c 2 track.wav track.raw

Read 節 17.6, “Creating and Using CD Media” for more information on using a CD burner in FreeBSD.

7.4. 播放影片

Contributed by Ross Lippert.

Video playback is a very new and rapidly developing application area. Be patient. Not everything is going to work as smoothly as it did with sound.

Before you begin, you should know the model of the video card you have and the chip it uses. While Xorg and XFree86 support a wide variety of video cards, fewer give good playback performance. To obtain a list of extensions supported by the X server using your card use the command xdpyinfo(1) while X11 is running.

It is a good idea to have a short MPEG file which can be treated as a test file for evaluating various players and options. Since some DVD players will look for DVD media in /dev/dvd by default, or have this device name hardcoded in them, you might find it useful to make symbolic links to the proper devices:

# ln -sf /dev/acd0c /dev/dvd
# ln -sf /dev/racd0c /dev/rdvd

On FreeBSD 5.X, which uses devfs(5) there is a slightly different set of recommended links:

# ln -sf /dev/acd0 /dev/dvd
# ln -sf /dev/acd0 /dev/rdvd

Note that due to the nature of devfs(5), manually created links like these will not persist if you reboot your system. In order to create the symbolic links automatically whenever you boot your system, add the following lines to /etc/devfs.conf:

link acd0 dvd
link acd0 rdvd

Additionally, DVD decryption, which requires invoking special DVD-ROM functions, requires write permission on the DVD devices.

Some of the ports discussed rely on the following kernel options to build correctly. Before attempting to build, add this option to the kernel configuration file, build a new kernel, and reboot:

options CPU_ENABLE_SSE

注意:

On FreeBSD 4.X options USER_LDT should be added to the kernel configuration file. This option is not available on FreeBSD 5.X and later version.

To enhance the shared memory X11 interface, it is recommended that the values of some sysctl(8) variables should be increased:

kern.ipc.shmmax=67108864
kern.ipc.shmall=32768

7.4.1. Determining Video Capabilities

There are several possible ways to display video under X11. What will really work is largely hardware dependent. Each method described below will have varying quality across different hardware. Secondly, the rendering of video in X11 is a topic receiving a lot of attention lately, and with each version of Xorg, or of XFree86, there may be significant improvement.

A list of common video interfaces:

  1. X11: normal X11 output using shared memory.

  2. XVideo: an extension to the X11 interface which supports video in any X11 drawable.

  3. SDL: the Simple Directmedia Layer.

  4. DGA: the Direct Graphics Access.

  5. SVGAlib: low level console graphics layer.

7.4.1.1. XVideo

Xorg and XFree86™ 4.X have an extension called XVideo (aka Xvideo, aka Xv, aka xv) which allows video to be directly displayed in drawable objects through a special acceleration. This extension provides very good quality playback even on low-end machines.

To check whether the extension is running, use xvinfo:

% xvinfo

XVideo is supported for your card if the result looks like:

X-Video Extension version 2.2
screen #0
  Adaptor #0: "Savage Streams Engine"
    number of ports: 1
    port base: 43
    operations supported: PutImage
    supported visuals:
      depth 16, visualID 0x22
      depth 16, visualID 0x23
    number of attributes: 5
      "XV_COLORKEY" (range 0 to 16777215)
              client settable attribute
              client gettable attribute (current value is 2110)
      "XV_BRIGHTNESS" (range -128 to 127)
              client settable attribute
              client gettable attribute (current value is 0)
      "XV_CONTRAST" (range 0 to 255)
              client settable attribute
              client gettable attribute (current value is 128)
      "XV_SATURATION" (range 0 to 255)
              client settable attribute
              client gettable attribute (current value is 128)
      "XV_HUE" (range -180 to 180)
              client settable attribute
              client gettable attribute (current value is 0)
    maximum XvImage size: 1024 x 1024
    Number of image formats: 7
      id: 0x32595559 (YUY2)
        guid: 59555932-0000-0010-8000-00aa00389b71
        bits per pixel: 16
        number of planes: 1
        type: YUV (packed)
      id: 0x32315659 (YV12)
        guid: 59563132-0000-0010-8000-00aa00389b71
        bits per pixel: 12
        number of planes: 3
        type: YUV (planar)
      id: 0x30323449 (I420)
        guid: 49343230-0000-0010-8000-00aa00389b71
        bits per pixel: 12
        number of planes: 3
        type: YUV (planar)
      id: 0x36315652 (RV16)
        guid: 52563135-0000-0000-0000-000000000000
        bits per pixel: 16
        number of planes: 1
        type: RGB (packed)
        depth: 0
        red, green, blue masks: 0x1f, 0x3e0, 0x7c00
      id: 0x35315652 (RV15)
        guid: 52563136-0000-0000-0000-000000000000
        bits per pixel: 16
        number of planes: 1
        type: RGB (packed)
        depth: 0
        red, green, blue masks: 0x1f, 0x7e0, 0xf800
      id: 0x31313259 (Y211)
        guid: 59323131-0000-0010-8000-00aa00389b71
        bits per pixel: 6
        number of planes: 3
        type: YUV (packed)
      id: 0x0
        guid: 00000000-0000-0000-0000-000000000000
        bits per pixel: 0
        number of planes: 0
        type: RGB (packed)
        depth: 1
        red, green, blue masks: 0x0, 0x0, 0x0

Also note that the formats listed (YUV2, YUV12, etc) are not present with every implementation of XVideo and their absence may hinder some players.

If the result looks like:

X-Video Extension version 2.2
screen #0
no adaptors present

Then XVideo is probably not supported for your card.

If XVideo is not supported for your card, this only means that it will be more difficult for your display to meet the computational demands of rendering video. Depending on your video card and processor, though, you might still be able to have a satisfying experience. You should probably read about ways of improving performance in the advanced reading 節 7.4.3, “Further Reading”.

7.4.1.2. Simple Directmedia Layer

The Simple Directmedia Layer, SDL, was intended to be a porting layer between Microsoft® Windows®, BeOS, and UNIX®, allowing cross-platform applications to be developed which made efficient use of sound and graphics. The SDL layer provides a low-level abstraction to the hardware which can sometimes be more efficient than the X11 interface.

The SDL can be found at devel/sdl12.

7.4.1.3. Direct Graphics Access

Direct Graphics Access is an X11 extension which allows a program to bypass the X server and directly alter the framebuffer. Because it relies on a low level memory mapping to effect this sharing, programs using it must be run as root.

The DGA extension can be tested and benchmarked by dga(1). When dga is running, it changes the colors of the display whenever a key is pressed. To quit, use q.

7.4.2. Ports and Packages Dealing with Video

This section discusses the software available from the FreeBSD Ports Collection which can be used for video playback. Video playback is a very active area of software development, and the capabilities of various applications are bound to diverge somewhat from the descriptions given here.

Firstly, it is important to know that many of the video applications which run on FreeBSD were developed as Linux applications. Many of these applications are still beta-quality. Some of the problems that you may encounter with video packages on FreeBSD include:

  1. An application cannot playback a file which another application produced.

  2. An application cannot playback a file which the application itself produced.

  3. The same application on two different machines, rebuilt on each machine for that machine, plays back the same file differently.

  4. A seemingly trivial filter like rescaling of the image size results in very bad artifacts from a buggy rescaling routine.

  5. An application frequently dumps core.

  6. Documentation is not installed with the port and can be found either on the web or under the port's work directory.

Many of these applications may also exhibit Linux-isms. That is, there may be issues resulting from the way some standard libraries are implemented in the Linux distributions, or some features of the Linux kernel which have been assumed by the authors of the applications. These issues are not always noticed and worked around by the port maintainers, which can lead to problems like these:

  1. The use of /proc/cpuinfo to detect processor characteristics.

  2. A misuse of threads which causes a program to hang upon completion instead of truly terminating.

  3. Software not yet in the FreeBSD Ports Collection which is commonly used in conjunction with the application.

So far, these application developers have been cooperative with port maintainers to minimize the work-arounds needed for port-ing.

7.4.2.1. MPlayer

MPlayer is a recently developed and rapidly developing video player. The goals of the MPlayer team are speed and flexibility on Linux and other Unices. The project was started when the team founder got fed up with bad playback performance on then available players. Some would say that the graphical interface has been sacrificed for a streamlined design. However, once you get used to the command line options and the key-stroke controls, it works very well.

7.4.2.1.1. Building MPlayer

MPlayer resides in multimedia/mplayer. MPlayer performs a variety of hardware checks during the build process, resulting in a binary which will not be portable from one system to another. Therefore, it is important to build it from ports and not to use a binary package. Additionally, a number of options can be specified in the make command line, as described in the Makefile and at the start of the build:

# cd /usr/ports/multimedia/mplayer
# make
N - O - T - E

Take a careful look into the Makefile in order
to learn how to tune mplayer towards you personal preferences!
For example,
make WITH_GTK1
builds MPlayer with GTK1-GUI support.
If you want to use the GUI, you can either install
/usr/ports/multimedia/mplayer-skins
or download official skin collections from
http://www.mplayerhq.hu/homepage/dload.html

The default port options should be sufficient for most users. However, if you need the XviD codec, you have to specify the WITH_XVID option in the command line. The default DVD device can also be defined with the WITH_DVD_DEVICE option, by default /dev/acd0 will be used.

As of this writing, the MPlayer port will build its HTML documentation and two executables, mplayer, and mencoder, which is a tool for re-encoding video.

The HTML documentation for MPlayer is very informative. If the reader finds the information on video hardware and interfaces in this chapter lacking, the MPlayer documentation is a very thorough supplement. You should definitely take the time to read the MPlayer documentation if you are looking for information about video support in UNIX®.

7.4.2.1.2. Using MPlayer

Any user of MPlayer must set up a .mplayer subdirectory of her home directory. To create this necessary subdirectory, you can type the following:

% cd /usr/ports/multimedia/mplayer
% make install-user

The command options for mplayer are listed in the manual page. For even more detail there is HTML documentation. In this section, we will describe only a few common uses.

To play a file, such as testfile.avi, through one of the various video interfaces set the -vo option:

% mplayer -vo xv testfile.avi
% mplayer -vo sdl testfile.avi
% mplayer -vo x11 testfile.avi
# mplayer -vo dga testfile.avi
# mplayer -vo 'sdl:dga' testfile.avi

It is worth trying all of these options, as their relative performance depends on many factors and will vary significantly with hardware.

To play from a DVD, replace the testfile.avi with dvd://N -dvd-device DEVICE where N is the title number to play and DEVICE is the device node for the DVD-ROM. For example, to play title 3 from /dev/dvd:

# mplayer -vo xv dvd://3 -dvd-device /dev/dvd

注意:

The default DVD device can be defined during the build of the MPlayer port via the WITH_DVD_DEVICE option. By default, this device is /dev/acd0. More details can be found in the port Makefile.

To stop, pause, advance and so on, consult the keybindings, which are output by running mplayer -h or read the manual page.

Additional important options for playback are: -fs -zoom which engages the fullscreen mode and -framedrop which helps performance.

In order for the mplayer command line to not become too large, the user can create a file .mplayer/config and set default options there:

vo=xv
fs=yes
zoom=yes

Finally, mplayer can be used to rip a DVD title into a .vob file. To dump out the second title from a DVD, type this:

# mplayer -dumpstream -dumpfile out.vob dvd://2 -dvd-device /dev/dvd

The output file, out.vob, will be MPEG and can be manipulated by the other packages described in this section.

7.4.2.1.3. mencoder

Before using mencoder it is a good idea to familiarize yourself with the options from the HTML documentation. There is a manual page, but it is not very useful without the HTML documentation. There are innumerable ways to improve quality, lower bitrate, and change formats, and some of these tricks may make the difference between good or bad performance. Here are a couple of examples to get you going. First a simple copy:

% mencoder input.avi -oac copy -ovc copy -o output.avi

Improper combinations of command line options can yield output files that are unplayable even by mplayer. Thus, if you just want to rip to a file, stick to the -dumpfile in mplayer.

To convert input.avi to the MPEG4 codec with MPEG3 audio encoding (audio/lame is required):

% mencoder input.avi -oac mp3lame -lameopts br=192 \
	 -ovc lavc -lavcopts vcodec=mpeg4:vhq -o output.avi

This has produced output playable by mplayer and xine.

input.avi can be replaced with dvd://1 -dvd-device /dev/dvd and run as root to re-encode a DVD title directly. Since you are likely to be dissatisfied with your results the first time around, it is recommended you dump the title to a file and work on the file.

7.4.2.2. The xine Video Player

The xine video player is a project of wide scope aiming not only at being an all in one video solution, but also in producing a reusable base library and a modular executable which can be extended with plugins. It comes both as a package and as a port, multimedia/xine.

The xine player is still very rough around the edges, but it is clearly off to a good start. In practice, xine requires either a fast CPU with a fast video card, or support for the XVideo extension. The GUI is usable, but a bit clumsy.

As of this writing, there is no input module shipped with xine which will play CSS encoded DVD's. There are third party builds which do have modules for this built in them, but none of these are in the FreeBSD Ports Collection.

Compared to MPlayer, xine does more for the user, but at the same time, takes some of the more fine-grained control away from the user. The xine video player performs best on XVideo interfaces.

By default, xine player will start up in a graphical user interface. The menus can then be used to open a specific file:

% xine

Alternatively, it may be invoked to play a file immediately without the GUI with the command:

% xine -g -p mymovie.avi

7.4.2.3. The transcode Utilities

The software transcode is not a player, but a suite of tools for re-encoding video and audio files. With transcode, one has the ability to merge video files, repair broken files, using command line tools with stdin/stdout stream interfaces.

A great number of options can be specified during the build from the multimedia/transcode port, we recommend the following command line to build transcode:

# make WITH_OPTIMIZED_CFLAGS=yes WITH_LIBA52=yes WITH_LAME=yes WITH_OGG=yes \
WITH_MJPEG=yes -DWITH_XVID=yes

The proposed settings should be sufficient for most users.

To illustrate transcode capacities, one example to show how to convert a DivX file into a PAL MPEG-1 file (PAL VCD):

% transcode -i input.avi -V --export_prof vcd-pal -o output_vcd
% mplex -f 1 -o output_vcd.mpg output_vcd.m1v output_vcd.mpa

The resulting MPEG file, output_vcd.mpg, is ready to be played with MPlayer. You could even burn the file on a CD-R media to create a Video CD, in this case you will need to install and use both multimedia/vcdimager and sysutils/cdrdao programs.

There is a manual page for transcode, but you should also consult the transcode wiki for further information and examples.

7.4.3. Further Reading

The various video software packages for FreeBSD are developing rapidly. It is quite possible that in the near future many of the problems discussed here will have been resolved. In the mean time, those who want to get the very most out of FreeBSD's A/V capabilities will have to cobble together knowledge from several FAQs and tutorials and use a few different applications. This section exists to give the reader pointers to such additional information.

The MPlayer documentation is very technically informative. These documents should probably be consulted by anyone wishing to obtain a high level of expertise with UNIX® video. The MPlayer mailing list is hostile to anyone who has not bothered to read the documentation, so if you plan on making bug reports to them, RTFM.

The xine HOWTO contains a chapter on performance improvement which is general to all players.

Finally, there are some other promising applications which the reader may try:

7.5. 設定電視卡(TV Cards)

Original contribution by Josef El-Rayes.
Enhanced and adapted by Marc Fonvieille.

7.5.1. 介紹

電視卡(TV card)可以讓您用電腦來看無線、有線電視節目。許多卡都是透過 RCA 或 S-video 輸入端子來接收視訊,而且有些卡還可接收 FM 廣播的功能。

FreeBSD 可透過 bktr(4) 驅動程式,來支援 PCI 介面的電視卡,只要這些卡使用的是 Brooktree Bt848/849/878/879 或 Conexant CN-878/Fusion 878a 視訊擷取晶片。此外,要再確認哪些卡上所附的選台功能是否有支援,可以參考 bktr(4) 說明,以查看所支援的硬體清單。

7.5.2. 設定相關驅動程式

要用電視卡的話,就要載入 bktr(4) 驅動程式,這個可以透過在 /boot/loader.conf 檔加上下面這一行就可以了:

bktr_load="YES"

此外,也可以把該 kernel module 直接與 kernel 編譯在一起,作法就是在你的 kernel 設定檔內,加上下面這幾行:

device	 bktr
device	iicbus
device	iicbb
device	smbus

之所以要加上這些額外的驅動程式,是因為卡的各組成部分都是透過 I2C 匯流排而相互連接的。接下來,請重新編譯、安裝新的 kernel 。

安裝好新的 kernel 之後,要重開機才會生效。開機時,應該會看到類似下面的正確偵測到 TV card 訊息:

bktr0: <BrookTree 848A> mem 0xd7000000-0xd7000fff irq 10 at device 10.0 on pci0
iicbb0: <I2C bit-banging driver> on bti2c0
iicbus0: <Philips I2C bus> on iicbb0 master-only
iicbus1: <Philips I2C bus> on iicbb0 master-only
smbus0: <System Management Bus> on bti2c0
bktr0: Pinnacle/Miro TV, Philips SECAM tuner.

當然,這些訊息可能因您的硬體不同而有所不同。However you should check if the tuner is correctly detected; it is still possible to override some of the detected parameters with sysctl(8) MIBs and kernel configuration file options. For example, if you want to force the tuner to a Philips SECAM tuner, you should add the following line to your kernel configuration file:

options OVERRIDE_TUNER=6

or you can directly use sysctl(8):

# sysctl hw.bt848.tuner=6

See the bktr(4) manual page and the /usr/src/sys/conf/NOTES file for more details on the available options. (If you are under FreeBSD 4.X, /usr/src/sys/conf/NOTES is replaced with /usr/src/sys/i386/conf/LINT.)

7.5.3. 好用的程式

要用電視卡,可以視需要安裝下列應用程式之一︰

  • multimedia/fxtv provides TV-in-a-window and image/audio/video capture capabilities.

  • multimedia/xawtv is also a TV application, with the same features as fxtv.

  • misc/alevt decodes and displays Videotext/Teletext.

  • audio/xmradio, an application to use the FM radio tuner coming with some TV cards.

  • audio/wmtune, a handy desktop application for radio tuners.

More applications are available in the FreeBSD Ports Collection.

7.5.4. Troubleshooting

If you encounter any problem with your TV card, you should check at first if the video capture chip and the tuner are really supported by the bktr(4) driver and if you used the right configuration options. For more support and various questions about your TV card you may want to contact and use the archives of the freebsd-multimedia mailing list.

7.6. 掃描器

Written by Marc Fonvieille.

7.6.1. 介紹

FreeBSD 就像任何現代作業系統一樣,都可以使用掃描器。 在 FreeBSD 是透過 Ports Collection 內的 SANE(Scanner Access Now Easy) 所提供的 API 來操作掃描器。 SANE 也會使用一些 FreeBSD 的驅動程式來控制掃描器硬體。

FreeBSD 同時支援 SCSI 和 USB 兩種介面的掃描器。在做任何設定之前,請確保 SANE 有支援您的掃描器。 SANE 有張 支援硬體 的清單,這裡有介紹掃描器的支援情況和狀態訊息。 在 uscanner(4) 內也有提供一份 USB 掃描器的支援列表。

7.6.2. Kernel 的設定

如同上述所提的 SCSI 和 USB 界面都有支援。這要取決於您的掃描器界面,而需要不同的設備驅動程式。

7.6.2.1. USB 介面

The GENERIC kernel by default includes the device drivers needed to support USB scanners. Should you decide to use a custom kernel, be sure that the following lines are present in your kernel configuration file:

device usb
device uhci
device ohci
device uscanner

Depending upon the USB chipset on your motherboard, you will only need either device uhci or device ohci, however having both in the kernel configuration file is harmless.

If you do not want to rebuild your kernel and your kernel is not the GENERIC one, you can directly load the uscanner(4) device driver module with the kldload(8) command:

# kldload uscanner

To load this module at each system startup, add the following line to /boot/loader.conf:

uscanner_load="YES"

After rebooting with the correct kernel, or after loading the required module, plug in your USB scanner. The scanner should appear in your system message buffer (dmesg(8)) as something like:

uscanner0: EPSON EPSON Scanner, rev 1.10/3.02, addr 2

This shows that our scanner is using the /dev/uscanner0 device node.

注意:

On FreeBSD 4.X, the USB daemon (usbd(8)) must be running to be able to see some USB devices. To enable this, add usbd_enable="YES" to your /etc/rc.conf file and reboot the machine.

7.6.2.2. SCSI 介面

If your scanner comes with a SCSI interface, it is important to know which SCSI controller board you will use. According to the SCSI chipset used, you will have to tune your kernel configuration file. The GENERIC kernel supports the most common SCSI controllers. Be sure to read the NOTES file (LINT under FreeBSD 4.X) and add the correct line to your kernel configuration file. In addition to the SCSI adapter driver, you need to have the following lines in your kernel configuration file:

device scbus
device pass

Once your kernel has been properly compiled, you should be able to see the devices in your system message buffer, when booting:

pass2 at aic0 bus 0 target 2 lun 0
pass2: <AGFA SNAPSCAN 600 1.10> Fixed Scanner SCSI-2 device
pass2: 3.300MB/s transfers

If your scanner was not powered-on at system boot, it is still possible to manually force the detection by performing a SCSI bus scan with the camcontrol(8) command:

# camcontrol rescan all
Re-scan of bus 0 was successful
Re-scan of bus 1 was successful
Re-scan of bus 2 was successful
Re-scan of bus 3 was successful

Then the scanner will appear in the SCSI devices list:

# camcontrol devlist
<IBM DDRS-34560 S97B>              at scbus0 target 5 lun 0 (pass0,da0)
<IBM DDRS-34560 S97B>              at scbus0 target 6 lun 0 (pass1,da1)
<AGFA SNAPSCAN 600 1.10>           at scbus1 target 2 lun 0 (pass3)
<PHILIPS CDD3610 CD-R/RW 1.00>     at scbus2 target 0 lun 0 (pass2,cd0)

More details about SCSI devices, are available in the scsi(4) and camcontrol(8) manual pages.

7.6.3. 設定 SANE

The SANE system has been splitted in two parts: the backends (graphics/sane-backends) and the frontends (graphics/sane-frontends). The backends part provides access to the scanner itself. The SANE's supported devices list specifies which backend will support your image scanner. It is mandatory to determine the correct backend for your scanner if you want to be able to use your device. The frontends part provides the graphical scanning interface (xscanimage).

The first thing to do is install the graphics/sane-backends port or package. Then, use the sane-find-scanner command to check the scanner detection by the SANE system:

# sane-find-scanner -q
found SCSI scanner "AGFA SNAPSCAN 600 1.10" at /dev/pass3

The output will show the interface type of the scanner and the device node used to attach the scanner to the system. The vendor and the product model may not appear, it is not important.

注意:

Some USB scanners require you to load a firmware, this is explained in the backend manual page. You should also read sane-find-scanner(1) and sane(7) manual pages.

Now we have to check if the scanner will be identified by a scanning frontend. By default, the SANE backends comes with a command line tool called scanimage(1). This command allows you to list the devices and to perform an image acquisition from the command line. The -L option is used to list the scanner device:

# scanimage -L
device `snapscan:/dev/pass3' is a AGFA SNAPSCAN 600 flatbed scanner

No output or a message saying that no scanners were identified indicates that scanimage(1) is unable to identify the scanner. If this happens, you will need to edit the backend configuration file and define the scanner device used. The /usr/local/etc/sane.d/ directory contains all backends configuration files. This identification problem does appear with certain USB scanners.

For example, with the USB scanner used in the 節 7.6.2.1, “USB 介面”, sane-find-scanner gives us the following information:

# sane-find-scanner -q
found USB scanner (UNKNOWN vendor and product) at device /dev/uscanner0

The scanner is correctly detected, it uses the USB interface and is attached to the /dev/uscanner0 device node. We can now check if the scanner is correctly identified:

# scanimage -L

No scanners were identified. If you were expecting something different,
check that the scanner is plugged in, turned on and detected by the
sane-find-scanner tool (if appropriate). Please read the documentation
which came with this software (README, FAQ, manpages).

Since the scanner is not identified, we will need to edit the /usr/local/etc/sane.d/epson.conf file. The scanner model used was the EPSON Perfection® 1650, so we know the scanner will use the epson backend. Be sure to read the help comments in the backends configuration files. Line changes are quite simple: comment out all lines that have the wrong interface for your scanner (in our case, we will comment out all lines starting with the word scsi as our scanner uses the USB interface), then add at the end of the file a line specifying the interface and the device node used. In this case, we add the following line:

usb /dev/uscanner0

Please be sure to read the comments provided in the backend configuration file as well as the backend manual page for more details and correct syntax to use. We can now verify if the scanner is identified:

# scanimage -L
device `epson:/dev/uscanner0' is a Epson GT-8200 flatbed scanner

Our USB scanner has been identified. It is not important if the brand and the model do not match. The key item to be concerned with is the `epson:/dev/uscanner0' field, which give us the right backend name and the right device node.

Once the scanimage -L command is able to see the scanner, the configuration is complete. The device is now ready to scan.

While scanimage(1) does allow us to perform an image acquisition from the command line, it is preferable to use a graphical user interface to perform image scanning. SANE offers a simple but efficient graphical interface: xscanimage (graphics/sane-frontends).

Xsane (graphics/xsane) is another popular graphical scanning frontend. This frontend offers advanced features such as various scanning mode (photocopy, fax, etc.), color correction, batch scans, etc. Both of these applications are useable as a GIMP plugin.

7.6.4. Allowing Scanner Access to Other Users

All previous operations have been done with root privileges. You may however, need other users to have access to the scanner. The user will need read and write permissions to the device node used by the scanner. As an example, our USB scanner uses the device node /dev/uscanner0 which is owned by the operator group. Adding the user joe to the operator group will allow him to use the scanner:

# pw groupmod operator -m joe

For more details read the pw(8) manual page. You also have to set the correct write permissions (0660 or 0664) on the /dev/uscanner0 device node, by default the operator group can only read the device node. This is done by adding the following lines to the /etc/devfs.rules file:

[system=5]
add path uscanner0 mode 660

Then add the following to /etc/rc.conf and reboot the machine:

devfs_system_ruleset="system"

More information regarding these lines can be found in the devfs(8) manual page. Under FreeBSD 4.X, the operator group has, by default, read and write permissions to /dev/uscanner0.

注意:

Of course, for security reasons, you should think twice before adding a user to any group, especially the operator group.

章 8. 設定 FreeBSD Kernel

更新、重排:Jim Mock.
原作為:Jake Hamby.

8.1. 概述

kernel 是整個 FreeBSD 作業系統的核心。 它控制了系統的整體運作,包含和記憶體管理、安全控管、網路、硬碟存取等等。 儘管目前 FreeBSD 大多可以用動態 module 來載入、卸載所需功能, 但有時候仍有必要學會重新調配 kernel。

讀完這章,您將了解︰

  • 為何需要重新調配、編譯 kernel?

  • 要怎麼修改 kernel 設定檔?

  • 如何以 kernel 設定檔來建立、編譯新的 kernel 呢?

  • 如何安裝新的 kernel。

  • 如何處理 kernel 錯誤無法開機的情形。

本章所舉例的相關指令都是以 root 權限來進行。

8.2. 為何需要重新調配、編譯 kernel?

早期的 FreeBSD 的 kernel 被戲稱為 monolithic kernel。 這意思是說當時的 kernel 是個大塊頭程式,且只支援固定的硬體而已。 如果您想改變 kernel 的設定,那麼必須編譯一個新的並重新開機,才能啟用。

現在的 FreeBSD 已快速成長到新型態的管理模式,其重要特色是: kernel 功能可以隨時依據需求, 而以動態載入或卸載相關的 kernel module。 這使得 kernel 能夠快速因應新的環境而作調整 (有點像是:筆記型電腦上的 PCMCIA 卡一樣即插即用) ,或是增加其他原本的預設 kernel(GENERIC)所沒有的功能。 這種模式,就叫做 modular kernel(核心模組)。

儘管如此,還是有一些功能仍須編譯在 kernel 內才行。因為有時候是因為這些功能與 kernel 結合的相當複雜緊密,而無法將它們弄成可動態載入的 module ;而有時候,則是因為沒有人有空來弄那些 kernel module 的實作。

重新調配、編譯 kernel 幾乎是每位 BSD 使用者所必須經歷的過程。 儘管這項工作可能比較耗時,但在 FreeBSD 的使用上會有許多好處。 跟必須支援大多數各式硬體的 GENERIC kernel 相比的話, 自行調配 kernel 不同處在於:可以更『體貼』,只支援『自己硬體』的部分就好。 好處在於,譬如︰

  • 開機速度更快:因為自行調配的 kernel 只需要偵測您系統上的硬體, 所以讓啟動所花的過程更流暢快速。

  • 佔用的記憶體更少:自行調配的 kernel 通常會比 GENERIC 核心使用更少的記憶體,由於 kernel 必須一直存放在記憶體內,因此這就顯得更加重要。因此, 對於記憶體較小的系統來說, 自行調配的 kernel 就可發揮更多的作用、揮灑空間。

  • 可支援更多硬體:您可在自行調配的 kernel 增加一些原本 GENERIC 核心沒有提供的硬體支援,像是音效卡之類的。

8.3. 探測系統硬體

Written by Tom Rhodes.

在進行 kernel 設定的探索之旅前, 先把該機器各項硬體資訊作點調查會是明智之舉。 若 FreeBSD 並非主要的作業系統,那麼也可以輕鬆透過目前所使用的作業系統, 來查看相關硬體資訊表。 舉例來說,Microsoft® 的 裝置管理員(Device Manager) 內通常會有目前有裝的硬體資訊。 而 裝置管理員 是在控制台。

注意:

Microsoft® Windows® 某些版本則是先透過 系統(System) 再進入 裝置管理員

若該機器尚未安裝任何作業系統,那麼就要親自找出相關硬體資訊。 其中一種方式是透過 dmesg(8) 以及 man(1)。 FreeBSD 上大多硬體都會有相關的 man 說明有支援的規格型號, 並且開機的偵測過程中,也會列出有找到的硬體。 舉個例子, 下面這幾行是說有偵測到滑鼠,並且是以 psm 驅動程式:

psm0: <PS/2 Mouse> irq 12 on atkbdc0
psm0: [GIANT-LOCKED]
psm0: [ITHREAD]
psm0: model Generic PS/2 mouse, device ID 0

驅動程式必須要在自訂的 kernel 設定檔內加入,或者是用 loader.conf(5)

dmesg 有時只顯示系統訊息而沒有開機偵測的部份, 遇到這種情況請查閱 /var/run/dmesg.boot 檔。

另外也可以透過 pciconf(8) 來列出更詳細的相關資訊。 舉例說明:

ath0@pci0:3:0:0:        class=0x020000 card=0x058a1014 chip=0x1014168c rev=0x01 hdr=0x00
    vendor     = 'Atheros Communications Inc.'
    device     = 'AR5212 Atheros AR5212 802.11abg wireless'
    class      = network
    subclass   = ethernet

上面顯示是透過 pciconf -lv 所看到的 ath 無線網卡驅動程式。 可以用 man ath 來查看 ath(4) 的相關說明。

在使用 man(1) 時,加上 -k 參數也可以提供比較精準的資訊。 以上述例子而言,可以改為打:

# man -k Atheros

就會列出有含上述關鍵字的相關 man 說明:

ath(4)                   - Atheros IEEE 802.11 wireless network driver
ath_hal(4)               - Atheros Hardware Access Layer (HAL)

知己知彼,先瞭解相關硬體環境,才能讓接下來的自訂 kernel 打造過程更為順利。

8.4. 重新調配、編譯 kernel

首先對 kernel 相關目錄作快速介紹。 這裡所提到的所有目錄都在 /usr/src/sys 內, 也可以用 /sys 這個 symbolic link 來連到這。 這裡的許多子目錄分別擺放 kernel 的各組成部分,但對打造 kernel 影響最重要的目錄是 arch/conf, 這裡是可以針對需求來修改自訂 kernel 相關設定。 此外,還有在編譯 kernel 過程中會暫時擺放的 compile 目錄。 剛講到的 arch 可以是右列架構之一: i386alphaamd64ia64powerpcsparc64pc98(在日本較流行的另一種 PC 硬體架構)。 在各特定硬體架構目錄的東西,只搭配相對應的硬體架構而已。 而其餘的原始碼則是與硬體架構無關,可以在所有 FreeBSD 可裝的平台上共用。 整體目錄架構都是有邏輯可循,像是各項有支援的硬體設備、檔案系統, 以及相關選項通常都會擺在它們自己的子目錄內。

本章所用到的例子,都是你使用 i386 架構的機器。 請依實際情況,對相關目錄作調整即可。

注意:

若您系統上 沒裝 /usr/src/sys 目錄, 也就是說沒裝 kernel source code 的話,那麼最簡單安裝方式就是以 root 權限來執行 sysinstall, 接著請選 Configure,然後選 Distributions 接著為 src 再選 base 最後選 sys。 若不喜歡用 sysinstall 而且手邊有 正式的 FreeBSD 光碟可以用的話, 那麼也可以用以下指令來安裝:

# mount /cdrom
# mkdir -p /usr/src/sys
# ln -s /usr/src/sys /sys
# cat /cdrom/src/ssys.[a-d]* | tar -xzvf -
# cat /cdrom/src/sbase.[a-d]* | tar -xzvf -

接下來,切換到 arch/conf 目錄, 複製 GENERIC 設定檔為你想稱呼的新 kernel 名稱。 例如:

# cd /usr/src/sys/i386/conf
# cp GENERIC MYKERNEL

通常,命名方式都是大寫。如果你負責維護許多不同硬體架構的 FreeBSD 機器的話,那麼照該機器名稱(hostname)來命名會是比較明智。 上面例子中之所以命名為 MYKERNEL 就是因為這緣故。

提示:

建議不要把改過的 kernel 設定檔直接放在 /usr/src。 因為若編譯遇到其他問題時, 直接砍掉 /usr/src 再重練, 可能會是比較乾脆的選擇之一。 一旦真的砍了之後,你可能幾秒之後才會醒悟到: 你同時也砍掉自己改的 kernel 設定檔。 此外,也不要直接修改 GENERIC,因為下次你 更新 source tree 時, 它會被新版覆蓋,而相關修改也將隨之而逝。

你也可考慮把 kernel 設定檔改放到其他地方,然後再到 i386 目錄內建個指向它的 symbolic link。

舉例:

# cd /usr/src/sys/i386/conf
# mkdir /root/kernels
# cp GENERIC /root/kernels/MYKERNEL
# ln -s /root/kernels/MYKERNEL

現在,就開始用自己喜歡的編輯器來修改 MYKERNEL。 若才剛裝好 FreeBSD 而已,唯一可用的編輯器很可能是 vi 了,由於它的用法很多種,礙於篇幅將不詳細介紹, 你可在 參考書目 內找到相關書籍。 不過,FreeBSD 也提供另一個更好用的編輯器,它叫做 ee,對新手而言,這可能是蠻好的選擇。 你可以任意修改檔案內的相關註解以說明相關設定為何, 或者其他想改的 GENERIC 設定內容。

若你有在 SunOS™ 或者其他種 BSD 作業系統下進行編譯 kernel 的經驗, 那麼應該已經很熟悉本篇所介紹的大部分步驟。 換句話說,若您之前用的是 DOS 這類作業系統,那麼 GENERIC 設定檔的內容就可能比較難懂些,沒關係, 我們將在下面的 kernel 設定 會循序漸進地介紹。

注意:

若有從 FreeBSD 計劃去更新你的 source tree 的話, 則切記在進行任何升級之前,務必要察看 /usr/src/UPDATING。 這檔會介紹在更新過程中的重大議題或要注意的事項。 由於 /usr/src/UPDATING 是對應於你機器上目前的 FreeBSD source code 版本,因此會提供比本手冊更新的內容。

現在開始來編譯 kernel 吧。

過程 8.1. 編譯 Kernel
  1. 請切換至 /usr/src 目錄:

    # cd /usr/src
  2. 編譯 kernel:

    # make buildkernel KERNCONF=MYKERNEL
  3. 安裝新 kernel:

    # make installkernel KERNCONF=MYKERNEL

注意:

要有完整的 FreeBSD source tree 才能編譯 kernel。

提示:

預設情況下,在編譯自訂 kernel 時,全部的 kernel modules 也會一起重編。 若要快速升級 kernel, 或是只想重編所需的 kernel module,那麼在編譯 kernel 前要先改一下 /etc/make.conf,比如:

MODULES_OVERRIDE = linux acpi sound/sound sound/driver/ds1 ntfs

上面該設定值為所希望重編的 kernel module 列表。

WITHOUT_MODULES = linux acpi sound/sound sound/driver/ds1 ntfs

而上面這設定值則為不要編入的 kernel module 列表。 若想更瞭解其他 kernel 編譯的相關變數,請參閱 make.conf(5) 說明。

新的 kernel 會複製到 /boot/kernel 目錄內的 /boot/kernel/kernel,而舊的則移至 /boot/kernel.old/kernel。 現在呢,先關機,然後就會以新 kernel 重開機 若有問題的話,本章後面會介紹一些疑難雜症來協助你。 若新 kernel 無法開機的話,請參閱 這裡 以恢復系統運作。

注意:

至於開機過程的其他相關檔案、設定,比如 loader(8) 及其設定,則放在 /boot。 Third party 或自訂的 kernel modules 則會放在 /boot/kernel,不過, 應注意要保持 kernel module 與 kernel 是否有同步, 這點很重要,否則會導致不穩或出問題。

8.5. kernel 設定檔解說

Updated for FreeBSD 6.X by Joel Dahl.

kernel 設定檔的內容格式相當簡單。 每一行都包括一個關鍵字,以及一個或多個參數。事實上, 很多行大多只有一個參數。任何以 # 開頭的敘述都將被視為註解而被忽略。 接下來將以在 GENERIC 所出現的順序一一介紹之。 若要看與該平台架構有關的各選項、設備列表, 請參閱與 GENERIC 檔同目錄的 NOTES 檔。 而與平台架構差異較無關的通用部份,則可參閱 /usr/src/sys/conf/NOTES

注意:

若為了測試,而需要一份含有所有可用設定的設定檔,那麼請以 root 身份下:

# cd /usr/src/sys/i386/conf && make LINT

下面為 GENERIC 設定檔的範例, 其中包括說明用的註釋。 這例子應該與您機器上的 /usr/src/sys/i386/conf/GENERIC 相當接近。

machine		i386

此處是指機器架構,必須為 alphaamd64i386ia64pc98powerpcsparc64 其中之一。

cpu          I486_CPU
cpu          I586_CPU
cpu          I686_CPU

上面設定是指定要用哪一種 CPU 型號。 也可以同時加上多組 CPU 型號 (比如說萬一不確定是否要用 I586_CPUI686_CPU)。 然而自訂 kernel 的話,建議先確認自己的 CPU 型號,然後只用最適合的那組就好了。 若不確定 CPU 到底是用哪一種, 可以查閱 /var/run/dmesg.boot 的開機訊息以確定。

ident          GENERIC

這是設定該 kernel 名稱為何,可以隨意命名之,像是取名為 MYKERNEL,若是有照先前說明來作大概會取這樣名字。 ident 後面的字串會在開機時顯示,因此若要辨認新 kernel 與常用 kernel 的話,就設定不同組名稱即可(比如在自訂實驗用的 kernel)。

#To statically compile in device wiring instead of /boot/device.hints
#hints          "GENERIC.hints"         # Default places to look for devices.

device.hints(5) 可用來設定各項驅動程式的選項。 開機時 loader(8) 會檢查預設的 /boot/device.hints 設定檔。 使用 hints 選項,就可以把這些 hints 靜態編入 kernel 內。 如此一來就不必在 /boot 內建立 device.hints 檔。

makeoptions     DEBUG=-g          # Build kernel with gdb(1) debug symbols

加上 -g 選項的話,FreeBSD 會在編譯過程加上 debug 用的資訊,透過這選項會讓 gcc(1) 啟用 debug 所會用到的相關資訊。

options          SCHED_4BSD         # 4BSD scheduler

FreeBSD. 傳統所用(並且是預設)的系統 CPU scheduler。 若您不清楚要如何設定 ,請保留這設定。

options          PREEMPTION         # Enable kernel thread preemption

Allows threads that are in the kernel to be preempted by higher priority threads. It helps with interactivity and allows interrupt threads to run sooner rather than waiting.

options          INET              # InterNETworking

Networking support. Leave this in, even if you do not plan to be connected to a network. Most programs require at least loopback networking (i.e., making network connections within your PC), so this is essentially mandatory.

options          INET6             # IPv6 communications protocols

This enables the IPv6 communication protocols.

options          FFS               # Berkeley Fast Filesystem

This is the basic hard drive file system. Leave it in if you boot from the hard disk.

options          SOFTUPDATES       # Enable FFS Soft Updates support

This option enables Soft Updates in the kernel, this will help speed up write access on the disks. Even when this functionality is provided by the kernel, it must be turned on for specific disks. Review the output from mount(8) to see if Soft Updates is enabled for your system disks. If you do not see the soft-updates option then you will need to activate it using the tunefs(8) (for existing file systems) or newfs(8) (for new file systems) commands.

options          UFS_ACL           # Support for access control lists

This option enables kernel support for access control lists. This relies on the use of extended attributes and UFS2, and the feature is described in detail in 節 13.9, “Access Control Lists”. ACLs are enabled by default and should not be disabled in the kernel if they have been used previously on a file system, as this will remove the access control lists, changing the way files are protected in unpredictable ways.

options          UFS_DIRHASH       # Improve performance on big directories

This option includes functionality to speed up disk operations on large directories, at the expense of using additional memory. You would normally keep this for a large server, or interactive workstation, and remove it if you are using FreeBSD on a smaller system where memory is at a premium and disk access speed is less important, such as a firewall.

options          MD_ROOT           # MD is a potential root device

This option enables support for a memory backed virtual disk used as a root device.

options          NFSCLIENT         # Network Filesystem Client
options          NFSSERVER         # Network Filesystem Server
options          NFS_ROOT          # NFS usable as /, requires NFSCLIENT

The network file system. Unless you plan to mount partitions from a UNIX® file server over TCP/IP, you can comment these out.

options          MSDOSFS           # MSDOS Filesystem

The MS-DOS® file system. Unless you plan to mount a DOS formatted hard drive partition at boot time, you can safely comment this out. It will be automatically loaded the first time you mount a DOS partition, as described above. Also, the excellent emulators/mtools software allows you to access DOS floppies without having to mount and unmount them (and does not require MSDOSFS at all).

options          CD9660            # ISO 9660 Filesystem

The ISO 9660 file system for CDROMs. Comment it out if you do not have a CDROM drive or only mount data CDs occasionally (since it will be dynamically loaded the first time you mount a data CD). Audio CDs do not need this file system.

options          PROCFS            # Process filesystem(requires PSEUDOFS)

The process file system. This is a pretend file system mounted on /proc which allows programs like ps(1) to give you more information on what processes are running. Use of PROCFS is not required under most circumstances, as most debugging and monitoring tools have been adapted to run without PROCFS: installs will not mount this file system by default.

options          PSEUDOFS          # Pseudo-filesystem framework

6.X kernels making use of PROCFS must also include support for PSEUDOFS.

options          GEOM_GPT          # GUID Partition Tables.

This option brings the ability to have a large number of partitions on a single disk.

options          COMPAT_43         # Compatible with BSD 4.3 [KEEP THIS!]

Compatibility with 4.3BSD. Leave this in; some programs will act strangely if you comment this out.

options          COMPAT_FREEBSD4   # Compatible with FreeBSD4

This option is required on FreeBSD 5.X i386™ and Alpha systems to support applications compiled on older versions of FreeBSD that use older system call interfaces. It is recommended that this option be used on all i386™ and Alpha systems that may run older applications; platforms that gained support only in 5.X, such as ia64 and Sparc64®, do not require this option.

options          COMPAT_FREEBSD5   # 與 FreeBSD5 相容

此行是 FreeBSD 6.X 及更新的版本若需支援 FreeBSD 5.X 系統呼叫才需要設定。

options          SCSI_DELAY=5000  # Delay (in ms) before probing SCSI

This causes the kernel to pause for 5 seconds before probing each SCSI device in your system. If you only have IDE hard drives, you can ignore this, otherwise you can try to lower this number, to speed up booting. Of course, if you do this and FreeBSD has trouble recognizing your SCSI devices, you will have to raise it again.

options          KTRACE            # ktrace(1) support

This enables kernel process tracing, which is useful in debugging.

options          SYSVSHM           # SYSV-style shared memory

This option provides for System V shared memory. The most common use of this is the XSHM extension in X, which many graphics-intensive programs will automatically take advantage of for extra speed. If you use X, you will definitely want to include this.

options          SYSVMSG           # SYSV-style message queues

Support for System V messages. This option only adds a few hundred bytes to the kernel.

options          SYSVSEM           # SYSV-style semaphores

Support for System V semaphores. Less commonly used but only adds a few hundred bytes to the kernel.

注意:

The -p option of the ipcs(1) command will list any processes using each of these System V facilities.

options 	     _KPOSIX_PRIORITY_SCHEDULING # POSIX P1003_1B real-time extensions

Real-time extensions added in the 1993 POSIX®. Certain applications in the Ports Collection use these (such as StarOffice).

options          KBD_INSTALL_CDEV  # install a CDEV entry in /dev

This option is required to allow the creation of keyboard device nodes in /dev.

options          ADAPTIVE_GIANT    # Giant mutex is adaptive.

Giant is the name of a mutual exclusion mechanism (a sleep mutex) that protects a large set of kernel resources. Today, this is an unacceptable performance bottleneck which is actively being replaced with locks that protect individual resources. The ADAPTIVE_GIANT option causes Giant to be included in the set of mutexes adaptively spun on. That is, when a thread wants to lock the Giant mutex, but it is already locked by a thread on another CPU, the first thread will keep running and wait for the lock to be released. Normally, the thread would instead go back to sleep and wait for its next chance to run. If you are not sure, leave this in.

注意:

Note that on FreeBSD 8.0-CURRENT and later versions, all mutexes are adaptive by default, unless explicitly set to non-adaptive by compiling with the NO_ADAPTIVE_MUTEXES option. As a result, Giant is adaptive by default now, and the ADAPTIVE_GIANT option has been removed from the kernel configuration.

device          apic               # I/O APIC

The apic device enables the use of the I/O APIC for interrupt delivery. The apic device can be used in both UP and SMP kernels, but is required for SMP kernels. Add options SMP to include support for multiple processors.

注意:

apic 只限 i386 架構才有,其他架構則不必加上這行。

device          eisa

Include this if you have an EISA motherboard. This enables auto-detection and configuration support for all devices on the EISA bus.

device          pci

Include this if you have a PCI motherboard. This enables auto-detection of PCI cards and gatewaying from the PCI to ISA bus.

# Floppy drives
device          fdc

This is the floppy drive controller.

# ATA and ATAPI devices
device          ata

This driver supports all ATA and ATAPI devices. You only need one device ata line for the kernel to detect all PCI ATA/ATAPI devices on modern machines.

device          atadisk                 # ATA disk drives

This is needed along with device ata for ATA disk drives.

device          ataraid                 # ATA RAID drives

This is needed along with device ata for ATA RAID drives.


device          atapicd                 # ATAPI CDROM drives

This is needed along with device ata for ATAPI CDROM drives.

device          atapifd                 # ATAPI floppy drives

This is needed along with device ata for ATAPI floppy drives.

device          atapist                 # ATAPI tape drives

This is needed along with device ata for ATAPI tape drives.

options         ATA_STATIC_ID           # Static device numbering

This makes the controller number static; without this, the device numbers are dynamically allocated.

# SCSI Controllers
device          ahb        # EISA AHA1742 family
device          ahc        # AHA2940 and onboard AIC7xxx devices
options         AHC_REG_PRETTY_PRINT    # Print register bitfields in debug
                                        # output.  Adds ~128k to driver.
device          ahd        # AHA39320/29320 and onboard AIC79xx devices
options         AHD_REG_PRETTY_PRINT    # Print register bitfields in debug
				        # output.  Adds ~215k to driver.
device          amd        # AMD 53C974 (Teckram DC-390(T))
device          isp        # Qlogic family
device          ispfw      # Firmware for QLogic HBAs- normally a module
device          mpt        # LSI-Logic MPT-Fusion
#device         ncr        # NCR/Symbios Logic
device          sym        # NCR/Symbios Logic (newer chipsets + those of `ncr')
device          trm        # Tekram DC395U/UW/F DC315U adapters

device          adv        # Advansys SCSI adapters
device          adw        # Advansys wide SCSI adapters
device          aha        # Adaptec 154x SCSI adapters
device          aic        # Adaptec 15[012]x SCSI adapters, AIC-6[23]60.
device          bt         # Buslogic/Mylex MultiMaster SCSI adapters

device          ncv        # NCR 53C500
device          nsp        # Workbit Ninja SCSI-3
device          stg        # TMC 18C30/18C50

SCSI controllers. Comment out any you do not have in your system. If you have an IDE only system, you can remove these altogether. The *_REG_PRETTY_PRINT lines are debugging options for their respective drivers.

# SCSI peripherals
device          scbus      # SCSI bus (required for SCSI)
device          ch         # SCSI media changers
device          da         # Direct Access (disks)
device          sa         # Sequential Access (tape etc)
device          cd         # CD
device          pass       # Passthrough device (direct SCSI access)
device          ses        # SCSI Environmental Services (and SAF-TE)

SCSI peripherals. Again, comment out any you do not have, or if you have only IDE hardware, you can remove them completely.

注意:

The USB umass(4) driver and a few other drivers use the SCSI subsystem even though they are not real SCSI devices. Therefore make sure not to remove SCSI support, if any such drivers are included in the kernel configuration.

# RAID controllers interfaced to the SCSI subsystem
device          amr        # AMI MegaRAID
device          arcmsr     # Areca SATA II RAID
device          asr        # DPT SmartRAID V, VI and Adaptec SCSI RAID
device          ciss       # Compaq Smart RAID 5*
device          dpt        # DPT Smartcache III, IV - See NOTES for options
device          hptmv      # Highpoint RocketRAID 182x
device          rr232x     # Highpoint RocketRAID 232x
device          iir        # Intel Integrated RAID
device          ips        # IBM (Adaptec) ServeRAID
device          mly        # Mylex AcceleRAID/eXtremeRAID
device          twa        # 3ware 9000 series PATA/SATA RAID

# RAID controllers
device          aac        # Adaptec FSA RAID
device          aacp       # SCSI passthrough for aac (requires CAM)
device          ida        # Compaq Smart RAID
device          mfi        # LSI MegaRAID SAS
device          mlx        # Mylex DAC960 family
device          pst        # Promise Supertrak SX6000
device          twe        # 3ware ATA RAID

Supported RAID controllers. If you do not have any of these, you can comment them out or remove them.

# atkbdc0 controls both the keyboard and the PS/2 mouse
device          atkbdc     # AT keyboard controller

The keyboard controller (atkbdc) provides I/O services for the AT keyboard and PS/2 style pointing devices. This controller is required by the keyboard driver (atkbd) and the PS/2 pointing device driver (psm).

device          atkbd      # AT keyboard

The atkbd driver, together with atkbdc controller, provides access to the AT 84 keyboard or the AT enhanced keyboard which is connected to the AT keyboard controller.

device          psm        # PS/2 mouse

Use this device if your mouse plugs into the PS/2 mouse port.

device          kbdmux        # keyboard multiplexer

多重鍵盤的支援。 若不打算同時接多組鍵盤的話, 那麼若要移除該行也沒關係。

device          vga        # VGA video card driver

The video card driver.

device          splash     # Splash screen and screen saver support

Splash screen at start up! Screen savers require this too.

# syscons is the default console driver, resembling an SCO console
device          sc

sc is the default console driver and resembles a SCO console. Since most full-screen programs access the console through a terminal database library like termcap, it should not matter whether you use this or vt, the VT220 compatible console driver. When you log in, set your TERM variable to scoansi if full-screen programs have trouble running under this console.

# Enable this for the pcvt (VT220 compatible) console driver
#device          vt
#options         XSERVER          # support for X server on a vt console
#options         FAT_CURSOR       # start with block cursor

This is a VT220-compatible console driver, backward compatible to VT100/102. It works well on some laptops which have hardware incompatibilities with sc. Also set your TERM variable to vt100 or vt220 when you log in. This driver might also prove useful when connecting to a large number of different machines over the network, where termcap or terminfo entries for the sc device are often not available —— vt100 should be available on virtually any platform.

device          agp

Include this if you have an AGP card in the system. This will enable support for AGP, and AGP GART for boards which have these features.

# Power management support (see NOTES for more options)
#device          apm

Advanced Power Management support. Useful for laptops, although in FreeBSD 5.X and above this is disabled in GENERIC by default.

# Add suspend/resume support for the i8254.
device           pmtimer

Timer device driver for power management events, such as APM and ACPI.

# PCCARD (PCMCIA) support
# PCMCIA and cardbus bridge support
device          cbb               # cardbus (yenta) bridge
device          pccard            # PC Card (16-bit) bus
device          cardbus           # CardBus (32-bit) bus

PCMCIA support. You want this if you are using a laptop.

# Serial (COM) ports
device          sio               # 8250, 16[45]50 based serial ports

These are the serial ports referred to as COM ports in the MS-DOS®/Windows® world.

注意:

If you have an internal modem on COM4 and a serial port at COM2, you will have to change the IRQ of the modem to 2 (for obscure technical reasons, IRQ2 = IRQ 9) in order to access it from FreeBSD. If you have a multiport serial card, check the manual page for sio(4) for more information on the proper values to add to your /boot/device.hints. Some video cards (notably those based on S3 chips) use IO addresses in the form of 0x*2e8, and since many cheap serial cards do not fully decode the 16-bit IO address space, they clash with these cards making the COM4 port practically unavailable.

Each serial port is required to have a unique IRQ (unless you are using one of the multiport cards where shared interrupts are supported), so the default IRQs for COM3 and COM4 cannot be used.

# Parallel port
device          ppc

This is the ISA-bus parallel port interface.

device          ppbus      # Parallel port bus (required)

Provides support for the parallel port bus.

device          lpt        # Printer

Support for parallel port printers.

注意:

All three of the above are required to enable parallel printer support.

device          plip       # TCP/IP over parallel

This is the driver for the parallel network interface.

device          ppi        # Parallel port interface device

The general-purpose I/O (geek port) + IEEE1284 I/O.

#device         vpo        # Requires scbus and da

This is for an Iomega Zip drive. It requires scbus and da support. Best performance is achieved with ports in EPP 1.9 mode.

#device         puc

Uncomment this device if you have a dumb serial or parallel PCI card that is supported by the puc(4) glue driver.

# PCI Ethernet NICs.
device          de         # DEC/Intel DC21x4x (Tulip)
device          em         # Intel PRO/1000 adapter Gigabit Ethernet Card
device          ixgb       # Intel PRO/10GbE Ethernet Card
device          txp        # 3Com 3cR990 (Typhoon)
device          vx         # 3Com 3c590, 3c595 (Vortex)

Various PCI network card drivers. Comment out or remove any of these not present in your system.

# PCI Ethernet NICs that use the common MII bus controller code.
# NOTE: Be sure to keep the 'device miibus' line in order to use these NICs!
device          miibus     # MII bus support

MII bus support is required for some PCI 10/100 Ethernet NICs, namely those which use MII-compliant transceivers or implement transceiver control interfaces that operate like an MII. Adding device miibus to the kernel config pulls in support for the generic miibus API and all of the PHY drivers, including a generic one for PHYs that are not specifically handled by an individual driver.

device          bce        # Broadcom BCM5706/BCM5708 Gigabit Ethernet
device          bfe        # Broadcom BCM440x 10/100 Ethernet
device          bge        # Broadcom BCM570xx Gigabit Ethernet
device          dc         # DEC/Intel 21143 and various workalikes
device          fxp        # Intel EtherExpress PRO/100B (82557, 82558)
device          lge        # Level 1 LXT1001 gigabit ethernet
device          msk        # Marvell/SysKonnect Yukon II Gigabit Ethernet
device          nge        # NatSemi DP83820 gigabit ethernet
device          nve        # nVidia nForce MCP on-board Ethernet Networking
device          pcn        # AMD Am79C97x PCI 10/100 (precedence over 'lnc')
device          re         # RealTek 8139C+/8169/8169S/8110S
device          rl         # RealTek 8129/8139
device          sf         # Adaptec AIC-6915 (Starfire)
device          sis        # Silicon Integrated Systems SiS 900/SiS 7016
device          sk         # SysKonnect SK-984x & SK-982x gigabit Ethernet
device          ste        # Sundance ST201 (D-Link DFE-550TX)
device          stge       # Sundance/Tamarack TC9021 gigabit Ethernet
device          ti         # Alteon Networks Tigon I/II gigabit Ethernet
device          tl         # Texas Instruments ThunderLAN
device          tx         # SMC EtherPower II (83c170 EPIC)
device          vge        # VIA VT612x gigabit ethernet
device          vr         # VIA Rhine, Rhine II
device          wb         # Winbond W89C840F
device          xl         # 3Com 3c90x (Boomerang, Cyclone)

Drivers that use the MII bus controller code.

# ISA Ethernet NICs.  pccard NICs included.
device          cs         # Crystal Semiconductor CS89x0 NIC
# 'device ed' requires 'device miibus'
device          ed         # NE[12]000, SMC Ultra, 3c503, DS8390 cards
device          ex         # Intel EtherExpress Pro/10 and Pro/10+
device          ep         # Etherlink III based cards
device          fe         # Fujitsu MB8696x based cards
device          ie         # EtherExpress 8/16, 3C507, StarLAN 10 etc.
device          lnc        # NE2100, NE32-VL Lance Ethernet cards
device          sn         # SMC's 9000 series of Ethernet chips
device          xe         # Xircom pccard Ethernet

# ISA devices that use the old ISA shims
#device         le

ISA Ethernet drivers. See /usr/src/sys/i386/conf/NOTES for details of which cards are supported by which driver.

# Wireless NIC cards
device          wlan       # 802.11 support

對 802.11 標準的支援。 若要無線上網,則需加上這行。

device          wlan_wep        # 802.11 WEP support
device          wlan_ccmp       # 802.11 CCMP support
device          wlan_tkip       # 802.11 TKIP support

對 802.11 加密設備的支援。 若要安全加密以及 802.11i 安全協定, 則需加上這行。

device          an         # Aironet 4500/4800 802.11 wireless NICs.
device          ath             # Atheros pci/cardbus NIC's
device          ath_hal         # Atheros HAL (Hardware Access Layer)
device          ath_rate_sample # SampleRate tx rate control for ath
device          an         # Aironet 4500/4800 802.11 wireless NICs.
device          awi        # BayStack 660 and others
device          ral        # Ralink Technology RT2500 wireless NICs.
device          wi         # WaveLAN/Intersil/Symbol 802.11 wireless NICs.
#device         wl         # Older non 802.11 Wavelan wireless NIC.

Support for various wireless cards.

# Pseudo devices
device   loop          # Network loopback

This is the generic loopback device for TCP/IP. If you telnet or FTP to localhost (a.k.a. 127.0.0.1) it will come back at you through this device. This is mandatory.

device   random        # Entropy device

Cryptographically secure random number generator.

device   ether         # Ethernet support

ether is only needed if you have an Ethernet card. It includes generic Ethernet protocol code.

device   sl            # Kernel SLIP

sl is for SLIP support. This has been almost entirely supplanted by PPP, which is easier to set up, better suited for modem-to-modem connection, and more powerful.

device   ppp           # Kernel PPP

This is for kernel PPP support for dial-up connections. There is also a version of PPP implemented as a userland application that uses tun and offers more flexibility and features such as demand dialing.

device   tun           # Packet tunnel.

This is used by the userland PPP software. See the PPP section of this book for more information.


device   pty           # Pseudo-ttys (telnet etc)

This is a pseudo-terminal or simulated login port. It is used by incoming telnet and rlogin sessions, xterm, and some other applications such as Emacs.

device   md            # Memory disks

Memory disk pseudo-devices.

device   gif           # IPv6 and IPv4 tunneling

This implements IPv6 over IPv4 tunneling, IPv4 over IPv6 tunneling, IPv4 over IPv4 tunneling, and IPv6 over IPv6 tunneling. The gif device is auto-cloning, and will create device nodes as needed.

device   faith         # IPv6-to-IPv4 relaying (translation)

This pseudo-device captures packets that are sent to it and diverts them to the IPv4/IPv6 translation daemon.

# The `bpf' device enables the Berkeley Packet Filter.
# Be aware of the administrative consequences of enabling this!
# Note that 'bpf' is required for DHCP.
device   bpf           # Berkeley packet filter

This is the Berkeley Packet Filter. This pseudo-device allows network interfaces to be placed in promiscuous mode, capturing every packet on a broadcast network (e.g., an Ethernet). These packets can be captured to disk and or examined with the tcpdump(1) program.

注意:

The bpf(4) device is also used by dhclient(8) to obtain the IP address of the default router (gateway) and so on. If you use DHCP, leave this uncommented.

# USB support
device          uhci          # UHCI PCI->USB interface
device          ohci          # OHCI PCI->USB interface
device          ehci          # EHCI PCI->USB interface (USB 2.0)
device          usb           # USB Bus (required)
#device         udbp          # USB Double Bulk Pipe devices
device          ugen          # Generic
device          uhid          # Human Interface Devices
device          ukbd          # Keyboard
device          ulpt          # Printer
device          umass         # Disks/Mass storage - Requires scbus and da
device          ums           # Mouse
device          ural          # Ralink Technology RT2500USB wireless NICs
device          urio          # Diamond Rio 500 MP3 player
device          uscanner      # Scanners
# USB Ethernet, requires mii
device          aue           # ADMtek USB Ethernet
device          axe           # ASIX Electronics USB Ethernet
device          cdce          # Generic USB over Ethernet
device          cue           # CATC USB Ethernet
device          kue           # Kawasaki LSI USB Ethernet
device          rue           # RealTek RTL8150 USB Ethernet

Support for various USB devices.

# FireWire support
device          firewire      # FireWire bus code
device          sbp           # SCSI over FireWire (Requires scbus and da)
device          fwe           # Ethernet over FireWire (non-standard!)

Support for various Firewire devices.

For more information and additional devices supported by FreeBSD, see /usr/src/sys/i386/conf/NOTES.

8.5.1. Large Memory Configurations (PAE)

Large memory configuration machines require access to more than the 4 gigabyte limit on User+Kernel Virtual Address (KVA) space. Due to this limitation, Intel added support for 36-bit physical address space access in the Pentium® Pro and later line of CPUs.

The Physical Address Extension (PAE) capability of the Intel® Pentium® Pro and later CPUs allows memory configurations of up to 64 gigabytes. FreeBSD provides support for this capability via the PAE kernel configuration option, available in all current release versions of FreeBSD. Due to the limitations of the Intel memory architecture, no distinction is made for memory above or below 4 gigabytes. Memory allocated above 4 gigabytes is simply added to the pool of available memory.

To enable PAE support in the kernel, simply add the following line to your kernel configuration file:

options		    PAE

注意:

The PAE support in FreeBSD is only available for Intel® IA-32 processors. It should also be noted, that the PAE support in FreeBSD has not received wide testing, and should be considered beta quality compared to other stable features of FreeBSD.

PAE support in FreeBSD has a few limitations:

  • A process is not able to access more than 4 gigabytes of VM space.

  • KLD modules cannot be loaded into a PAE enabled kernel, due to the differences in the build framework of a module and the kernel.

  • Device drivers that do not use the bus_dma(9) interface will cause data corruption in a PAE enabled kernel and are not recommended for use. For this reason, a PAE kernel configuration file is provided in FreeBSD which excludes all drivers not known to work in a PAE enabled kernel.

  • Some system tunables determine memory resource usage by the amount of available physical memory. Such tunables can unnecessarily over-allocate due to the large memory nature of a PAE system. One such example is the kern.maxvnodes sysctl, which controls the maximum number of vnodes allowed in the kernel. It is advised to adjust this and other such tunables to a reasonable value.

  • It might be necessary to increase the kernel virtual address (KVA) space or to reduce the amount of specific kernel resource that is heavily used (see above) in order to avoid KVA exhaustion. The KVA_PAGES kernel option can be used for increasing the KVA space.

For performance and stability concerns, it is advised to consult the tuning(7) manual page. The pae(4) manual page contains up-to-date information on FreeBSD's PAE support.

8.6. If Something Goes Wrong

There are five categories of trouble that can occur when building a custom kernel. They are:

config fails:

If the config(8) command fails when you give it your kernel description, you have probably made a simple error somewhere. Fortunately, config(8) will print the line number that it had trouble with, so that you can quickly locate the line containing the error. For example, if you see:

config: line 17: syntax error

Make sure the keyword is typed correctly by comparing it to the GENERIC kernel or another reference.

make fails:

If the make command fails, it usually signals an error in your kernel description which is not severe enough for config(8) to catch. Again, look over your configuration, and if you still cannot resolve the problem, send mail to the FreeBSD general questions 郵遞論壇 with your kernel configuration, and it should be diagnosed quickly.

The kernel does not boot:

If your new kernel does not boot, or fails to recognize your devices, do not panic! Fortunately, FreeBSD has an excellent mechanism for recovering from incompatible kernels. Simply choose the kernel you want to boot from at the FreeBSD boot loader. You can access this when the system boot menu appears. Select the Escape to a loader prompt option, number six. At the prompt, type unload kernel and then type boot /boot/kernel.old/kernel, or the filename of any other kernel that will boot properly. When reconfiguring a kernel, it is always a good idea to keep a kernel that is known to work on hand.

After booting with a good kernel you can check over your configuration file and try to build it again. One helpful resource is the /var/log/messages file which records, among other things, all of the kernel messages from every successful boot. Also, the dmesg(8) command will print the kernel messages from the current boot.

注意:

If you are having trouble building a kernel, make sure to keep a GENERIC, or some other kernel that is known to work on hand as a different name that will not get erased on the next build. You cannot rely on kernel.old because when installing a new kernel, kernel.old is overwritten with the last installed kernel which may be non-functional. Also, as soon as possible, move the working kernel to the proper /boot/kernel location or commands such as ps(1) may not work properly. To do this, simply rename the directory containing the good kernel:

# mv /boot/kernel /boot/kernel.bad
# mv /boot/kernel.good /boot/kernel
The kernel works, but ps(1) does not work any more:

If you have installed a different version of the kernel from the one that the system utilities have been built with, for example, a -CURRENT kernel on a -RELEASE, many system-status commands like ps(1) and vmstat(8) will not work any more. You should recompile and install a world built with the same version of the source tree as your kernel. This is one reason it is not normally a good idea to use a different version of the kernel from the rest of the operating system.

章 9. 列印

Contributed by Sean Kelly.
Restructured and updated by Jim Mock.

9.1. 概述

FreeBSD 可以和各式各樣的印表機搭配列印, 從最老的撞針式印表機到最新的雷射印表機都沒問題, 讓您的應用程式可以產生出高品質的文件列印輸出。

也可以把 FreeBSD 設定成一台網路列印伺服器;這時候的 FreeBSD 能接收其他電腦送來的列印工作,包括其他 FreeBSD 的電腦、Windows® 的電腦以及 Mac OS® 的電腦。 FreeBSD 會確保同時只有一件文件正在列印,而且可以統計哪個使用者及機器印得最多, 還有就是印出接下來是誰的文件這類的標題頁等。

讀完這章,您將了解:

  • 如何設定 FreeBSD 的列印多工緩衝處理器。

  • 如何安裝列印過濾器以分別處理特殊的列印工作, 包括把收到的文件轉換成您的印表機看得懂的列印格式等。

  • 了解如何在您列印時順便印出頁首或標題。

  • 如何利用別台電腦上的印表機列印。

  • 如何利用直接接在網路上的印表機列印。

  • 如何控制印表機的權限,包括限制列印工作的檔案大小, 以及不允許特定使用者列印等。

  • 如何記下印表機的統計資料,以及各帳號的印表機使用量。

  • 如何解決列印時遇到的問題。

在開始閱讀這章之前,您需要︰

9.2. 介紹

要在 FreeBSD 上使用印表機,您需要設定好 Berkeley 行列式印表機列印緩衝系統,又稱為 LPD 列印緩衝系統,或者就叫他 LPD 吧。 這是 FreeBSD 標準的印表機控制系統,本章會介紹並教您如何設定 LPD

如果您已經對 LPD 或是其他列印緩衝系統很熟悉了, 您可以直接跳到基本設定

LPD 控制著主機上印表機的一切。 它負責這些工作:

  • 控制本機及網路印表機的使用。

  • 讓使用者可以列印文件,送出的文件稱為工作

  • 為每台印表機準備一個佇列, 避免多個使用者同時使用同一台印表機。

  • 列印 header pages (又稱為 banner or burst pages),方便使用者在出紙閘中找到自已列印的文件。

  • 把接在串列埠上的印表機的通訊參數設定好。

  • 利用網路傳送列印工作給別台主機上的 LPD

  • 執行特別的過濾程式將列印工作格式化以配合不同的列印語言或印表機。

  • 統計印表機的使用情況。

藉由設定檔 (/etc/printcap) 以及過濾程式的幫助, 您可以讓大多數的印表機配合 LPD 達成上述全部或部份的功能。

9.2.1. 為什麼需要使用多工緩衝處理器

如果您的系統是個人使用, 不需要控制存取權限、列印標題頁或者統計使用情況等功能時, 您可能會覺得很奇怪為什麼還需要去管這個多工緩衝處理器。 當然要直接控制印表機可行的, 不過無論如何您還是需要多工緩衝處理器,因為:

  • LPD 可以在背景 (background) 列印,您不需要在那邊等文件送到印表機。

  • LPD 可以很輕鬆地用過濾器增加日期 / 時間於頁首或是把特別的檔案格式 (像是 TeX DVI 檔) 轉換成印表機看得懂的的格式,您不需要手動去做這些步驟。

  • 許多免費或商業軟體提供的列印功能通常都是和多工緩衝處理器溝通。 透過設定緩衝系統,支援您現有或是即將要安裝的其他軟體將變得更容易。

9.3. 基礎設定

要用印表機搭配 LPD 多工緩衝系統,您需要有印表機這個硬體以及 LPD 這套軟體。 本手冊提供了兩階段的設定說明:

  • 閱讀 簡易印表機設定 來學習如何連接印表機、讓印表機和 LPD 溝通以及列印純文字文件。

  • 閱讀 進階印表機設定 來學習如何列印各種特殊格式文件、列印首頁、網路列印、 控制印表機權限以及統計使用狀況等。

9.3.1. 簡易印表機設定

本章節會告訴您如何設定印表機設備和 LPD 軟體以使用印表機, 基本教學內容:

  • 硬體設定 會提示如何將印表機接上電腦的連接埠。

  • 軟體設定 會示範如何寫 LPD 緩衝器設定檔 (/etc/printcap)。

如果您要把印表機設定接收網路列印資料而不是本機端的話,請參考 印表機及網路資料傳輸介面

這個章節雖然叫做簡易印表機設定, 實際上還是有點複雜的。 最困難的部份是讓你的印表機和電腦上的 LPD 緩衝器能夠正常運作。 一旦印表機可以正常工作之後, 像是印首頁或是做列印統計這些進階的功能就不難做到了。

9.3.1.1. 硬體設定

本章節討論各種連接印表機到 PC 的方式。 這裡會提到不同種類的連接埠和連接線, 以及為了讓 FreeBSD 能和印表機溝通您可能會需要開啟的核心參數等。

如果您已經把印表機接上電腦, 而且在其他作業系統上有成功列印過的話,可以直接跳至 軟體設定

9.3.1.1.1. 連接埠和排線

市售個人電腦印表機一般來說不出這三種界面:

  • 序列 (Serial) 界面,又稱為 RS-232 或 COM 埠, 用您電腦上的序列埠傳送資料到印表機。 序列界面廣泛的為電腦業界所採用, 所以排線容易取得,要設定連線並不困難。 然而序列介面有時候會需要使用較特別的排線, 這時候就有可能需要設定一些較為複雜的通訊參數了。 大部份 PC 序列埠的傳輸速度最高只到 115200 bps, 因此想要用序列埠來列印大圖是不切實際的。

  • 並列 (Parallel) 界面利用電腦的並列埠將資料送到印表機。 並列埠比 RS-232 序列埠還快,也是一種電腦業界常用的界面。 這種界面的排線非常容易取得,但是較難用手工打造。 通常來說並列界面並沒有什麼通訊參數需要指定, 所以設定起來超級容易。

    並列埠界面有時候也會被稱為 Centronics 界面,這是印表機的接頭的名稱。

  • USB 界面,也就是通用序列匯流排,傳輸速率比並列界面或是 RS-232 序列界面都來得快,而且 USB 排線單純又便宜。 對列印工作而言,USB 比 RS-232 序列埠或是並列埠都來得好,但是在 UNIX® 系統上的支援度較差。 購買同時具有 USB 及並列埠兩種界面的印表機可以避免掉這種問題。

一般而言,並列界面只能提供單向傳輸 (電腦至印表機),而要用 USB 才能提供雙向。 然而在 FreeBSD 下,使用較新的並列埠 (EPP 和 ECP) 以及印表機,再配合使用 IEEE-1284 相容排線也可以做到雙向溝通。

電腦和印表機之間藉由並列埠行進雙向溝通的方式有兩種。 第一種是使用特製的、能和特定印表機溝通的 FreeBSD 印表機驅動程式。 這種方式在噴墨印表機上很常見,用來回報墨水存量以及其他狀態資訊等。 第二種方法是用 PostScript®,如果印表機有支援的話。

PostScript® jobs are actually programs sent to the printer; they need not produce paper at all and may return results directly to the computer. PostScript® also uses two-way communication to tell the computer about problems, such as errors in the PostScript® program or paper jams. Your users may be appreciative of such information. Furthermore, the best way to do effective accounting with a PostScript® printer requires two-way communication: you ask the printer for its page count (how many pages it has printed in its lifetime), then send the user's job, then ask again for its page count. Subtract the two values and you know how much paper to charge to the user.

9.3.1.1.2. Parallel Ports

To hook up a printer using a parallel interface, connect the Centronics cable between the printer and the computer. The instructions that came with the printer, the computer, or both should give you complete guidance.

Remember which parallel port you used on the computer. The first parallel port is ppc0 to FreeBSD; the second is ppc1, and so on. The printer device name uses the same scheme: /dev/lpt0 for the printer on the first parallel ports etc.

9.3.1.1.3. Serial Ports

To hook up a printer using a serial interface, connect the proper serial cable between the printer and the computer. The instructions that came with the printer, the computer, or both should give you complete guidance.

If you are unsure what the proper serial cable is, you may wish to try one of the following alternatives:

  • A modem cable connects each pin of the connector on one end of the cable straight through to its corresponding pin of the connector on the other end. This type of cable is also known as a DTE-to-DCE cable.

  • A null-modem cable connects some pins straight through, swaps others (send data to receive data, for example), and shorts some internally in each connector hood. This type of cable is also known as a DTE-to-DTE cable.

  • A serial printer cable, required for some unusual printers, is like the null-modem cable, but sends some signals to their counterparts instead of being internally shorted.

You should also set up the communications parameters for the printer, usually through front-panel controls or DIP switches on the printer. Choose the highest bps (bits per second, sometimes baud rate) that both your computer and the printer can support. Choose 7 or 8 data bits; none, even, or odd parity; and 1 or 2 stop bits. Also choose a flow control protocol: either none, or XON/XOFF (also known as in-band or software) flow control. Remember these settings for the software configuration that follows.

9.3.1.2. Software Setup

This section describes the software setup necessary to print with the LPD spooling system in FreeBSD.

Here is an outline of the steps involved:

  1. Configure your kernel, if necessary, for the port you are using for the printer; section Kernel Configuration tells you what you need to do.

  2. Set the communications mode for the parallel port, if you are using a parallel port; section Setting the Communication Mode for the Parallel Port gives details.

  3. Test if the operating system can send data to the printer. Section Checking Printer Communications gives some suggestions on how to do this.

  4. Set up LPD for the printer by modifying the file /etc/printcap. You will find out how to do this later in this chapter.

9.3.1.2.1. Kernel Configuration

The operating system kernel is compiled to work with a specific set of devices. The serial or parallel interface for your printer is a part of that set. Therefore, it might be necessary to add support for an additional serial or parallel port if your kernel is not already configured for one.

To find out if the kernel you are currently using supports a serial interface, type:

# grep sioN /var/run/dmesg.boot

Where N is the number of the serial port, starting from zero. If you see output similar to the following:

sio2 at port 0x3e8-0x3ef irq 5 on isa
sio2: type 16550A

then the kernel supports the port.

To find out if the kernel supports a parallel interface, type:

# grep ppcN /var/run/dmesg.boot

Where N is the number of the parallel port, starting from zero. If you see output similar to the following:

ppc0: <Parallel port> at port 0x378-0x37f irq 7 on isa0
ppc0: SMC-like chipset (ECP/EPP/PS2/NIBBLE) in COMPATIBLE mode
ppc0: FIFO with 16/16/8 bytes threshold

then the kernel supports the port.

You might have to reconfigure your kernel in order for the operating system to recognize and use the parallel or serial port you are using for the printer.

To add support for a serial port, see the section on kernel configuration. To add support for a parallel port, see that section and the section that follows.

9.3.1.3. Setting the Communication Mode for the Parallel Port

When you are using the parallel interface, you can choose whether FreeBSD should use interrupt-driven or polled communication with the printer. The generic printer device driver (lpt(4)) on FreeBSD uses the ppbus(4) system, which controls the port chipset with the ppc(4) driver.

  • The interrupt-driven method is the default with the GENERIC kernel. With this method, the operating system uses an IRQ line to determine when the printer is ready for data.

  • The polled method directs the operating system to repeatedly ask the printer if it is ready for more data. When it responds ready, the kernel sends more data.

The interrupt-driven method is usually somewhat faster but uses up a precious IRQ line. Some newer HP printers are claimed not to work correctly in interrupt mode, apparently due to some (not yet exactly understood) timing problem. These printers need polled mode. You should use whichever one works. Some printers will work in both modes, but are painfully slow in interrupt mode.

You can set the communications mode in two ways: by configuring the kernel or by using the lptcontrol(8) program.

To set the communications mode by configuring the kernel:

  1. Edit your kernel configuration file. Look for an ppc0 entry. If you are setting up the second parallel port, use ppc1 instead. Use ppc2 for the third port, and so on.

    • If you want interrupt-driven mode, edit the following line:

      hint.ppc.0.irq="N"

      in the /boot/device.hints file and replace N with the right IRQ number. The kernel configuration file must also contain the ppc(4) driver:

      device ppc
    • If you want polled mode, remove in your /boot/device.hints file, the following line:

      hint.ppc.0.irq="N"

      In some cases, this is not enough to put the port in polled mode under FreeBSD. Most of time it comes from acpi(4) driver, this latter is able to probe and attach devices, and therefore, control the access mode to the printer port. You should check your acpi(4) configuration to correct this problem.

  2. Save the file. Then configure, build, and install the kernel, then reboot. See kernel configuration for more details.

To set the communications mode with lptcontrol(8):

  1. Type:

    # lptcontrol -i -d /dev/lptN

    to set interrupt-driven mode for lptN.

  2. Type:

    # lptcontrol -p -d /dev/lptN

    to set polled-mode for lptN.

You could put these commands in your /etc/rc.local file to set the mode each time your system boots. See lptcontrol(8) for more information.

9.3.1.4. Checking Printer Communications

Before proceeding to configure the spooling system, you should make sure the operating system can successfully send data to your printer. It is a lot easier to debug printer communication and the spooling system separately.

To test the printer, we will send some text to it. For printers that can immediately print characters sent to them, the program lptest(1) is perfect: it generates all 96 printable ASCII characters in 96 lines.

For a PostScript® (or other language-based) printer, we will need a more sophisticated test. A small PostScript® program, such as the following, will suffice:

%!PS
100 100 moveto 300 300 lineto stroke
310 310 moveto /Helvetica findfont 12 scalefont setfont
(Is this thing working?) show
showpage

The above PostScript® code can be placed into a file and used as shown in the examples appearing in the following sections.

注意:

When this document refers to a printer language, it is assuming a language like PostScript®, and not Hewlett Packard's PCL. Although PCL has great functionality, you can intermingle plain text with its escape sequences. PostScript® cannot directly print plain text, and that is the kind of printer language for which we must make special accommodations.

9.3.1.4.1. Checking a Parallel Printer

This section tells you how to check if FreeBSD can communicate with a printer connected to a parallel port.

To test a printer on a parallel port:

  1. Become root with su(1).

  2. Send data to the printer.

    • If the printer can print plain text, then use lptest(1). Type:

      # lptest > /dev/lptN

      Where N is the number of the parallel port, starting from zero.

    • If the printer understands PostScript® or other printer language, then send a small program to the printer. Type:

      # cat > /dev/lptN

      Then, line by line, type the program carefully as you cannot edit a line once you have pressed RETURN or ENTER. When you have finished entering the program, press CONTROL+D, or whatever your end of file key is.

      Alternatively, you can put the program in a file and type:

      # cat file > /dev/lptN

      Where file is the name of the file containing the program you want to send to the printer.

You should see something print. Do not worry if the text does not look right; we will fix such things later.

9.3.1.4.2. Checking a Serial Printer

This section tells you how to check if FreeBSD can communicate with a printer on a serial port.

To test a printer on a serial port:

  1. Become root with su(1).

  2. Edit the file /etc/remote. Add the following entry:

    printer:dv=/dev/port:br#bps-rate:pa=parity

    Where port is the device entry for the serial port (ttyd0, ttyd1, etc.), bps-rate is the bits-per-second rate at which the printer communicates, and parity is the parity required by the printer (either even, odd, none, or zero).

    Here is a sample entry for a printer connected via a serial line to the third serial port at 19200 bps with no parity:

    printer:dv=/dev/ttyd2:br#19200:pa=none
  3. Connect to the printer with tip(1). Type:

    # tip printer

    If this step does not work, edit the file /etc/remote again and try using /dev/cuaaN instead of /dev/ttydN.

  4. Send data to the printer.

    • If the printer can print plain text, then use lptest(1). Type:

      % $lptest
    • If the printer understands PostScript® or other printer language, then send a small program to the printer. Type the program, line by line, very carefully as backspacing or other editing keys may be significant to the printer. You may also need to type a special end-of-file key for the printer so it knows it received the whole program. For PostScript® printers, press CONTROL+D.

      Alternatively, you can put the program in a file and type:

      % >file

      Where file is the name of the file containing the program. After tip(1) sends the file, press any required end-of-file key.

You should see something print. Do not worry if the text does not look right; we will fix that later.

9.3.1.5. Enabling the Spooler: the /etc/printcap File

At this point, your printer should be hooked up, your kernel configured to communicate with it (if necessary), and you have been able to send some simple data to the printer. Now, we are ready to configure LPD to control access to your printer.

You configure LPD by editing the file /etc/printcap. The LPD spooling system reads this file each time the spooler is used, so updates to the file take immediate effect.

The format of the printcap(5) file is straightforward. Use your favorite text editor to make changes to /etc/printcap. The format is identical to other capability files like /usr/share/misc/termcap and /etc/remote. For complete information about the format, see the cgetent(3).

The simple spooler configuration consists of the following steps:

  1. Pick a name (and a few convenient aliases) for the printer, and put them in the /etc/printcap file; see the Naming the Printer section for more information on naming.

  2. Turn off header pages (which are on by default) by inserting the sh capability; see the Suppressing Header Pages section for more information.

  3. Make a spooling directory, and specify its location with the sd capability; see the Making the Spooling Directory section for more information.

  4. Set the /dev entry to use for the printer, and note it in /etc/printcap with the lp capability; see the Identifying the Printer Device for more information. Also, if the printer is on a serial port, set up the communication parameters with the ms# capability which is discussed in the Configuring Spooler Communications Parameters section.

  5. Install a plain text input filter; see the Installing the Text Filter section for details.

  6. Test the setup by printing something with the lpr(1) command. More details are available in the Trying It Out and Troubleshooting sections.

注意:

Language-based printers, such as PostScript® printers, cannot directly print plain text. The simple setup outlined above and described in the following sections assumes that if you are installing such a printer you will print only files that the printer can understand.

Users often expect that they can print plain text to any of the printers installed on your system. Programs that interface to LPD to do their printing usually make the same assumption. If you are installing such a printer and want to be able to print jobs in the printer language and print plain text jobs, you are strongly urged to add an additional step to the simple setup outlined above: install an automatic plain-text-to-PostScript® (or other printer language) conversion program. The section entitled Accommodating Plain Text Jobs on PostScript® Printers tells how to do this.

9.3.1.5.1. Naming the Printer

The first (easy) step is to pick a name for your printer. It really does not matter whether you choose functional or whimsical names since you can also provide a number of aliases for the printer.

At least one of the printers specified in the /etc/printcap should have the alias lp. This is the default printer's name. If users do not have the PRINTER environment variable nor specify a printer name on the command line of any of the LPD commands, then lp will be the default printer they get to use.

Also, it is common practice to make the last alias for a printer be a full description of the printer, including make and model.

Once you have picked a name and some common aliases, put them in the /etc/printcap file. The name of the printer should start in the leftmost column. Separate each alias with a vertical bar and put a colon after the last alias.

In the following example, we start with a skeletal /etc/printcap that defines two printers (a Diablo 630 line printer and a Panasonic KX-P4455 PostScript® laser printer):

#
#  /etc/printcap for host rose
#
rattan|line|diablo|lp|Diablo 630 Line Printer:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:

In this example, the first printer is named rattan and has as aliases line, diablo, lp, and Diablo 630 Line Printer. Since it has the alias lp, it is also the default printer. The second is named bamboo, and has as aliases ps, PS, S, panasonic, and Panasonic KX-P4455 PostScript v51.4.

9.3.1.5.2. Suppressing Header Pages

The LPD spooling system will by default print a header page for each job. The header page contains the user name who requested the job, the host from which the job came, and the name of the job, in nice large letters. Unfortunately, all this extra text gets in the way of debugging the simple printer setup, so we will suppress header pages.

To suppress header pages, add the sh capability to the entry for the printer in /etc/printcap. Here is an example /etc/printcap with sh added:

#
#  /etc/printcap for host rose - no header pages anywhere
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:

Note how we used the correct format: the first line starts in the leftmost column, and subsequent lines are indented. Every line in an entry except the last ends in a backslash character.

9.3.1.5.3. Making the Spooling Directory

The next step in the simple spooler setup is to make a spooling directory, a directory where print jobs reside until they are printed, and where a number of other spooler support files live.

Because of the variable nature of spooling directories, it is customary to put these directories under /var/spool. It is not necessary to backup the contents of spooling directories, either. Recreating them is as simple as running mkdir(1).

It is also customary to make the directory with a name that is identical to the name of the printer, as shown below:

# mkdir /var/spool/printer-name

However, if you have a lot of printers on your network, you might want to put the spooling directories under a single directory that you reserve just for printing with LPD. We will do this for our two example printers rattan and bamboo:

# mkdir /var/spool/lpd
# mkdir /var/spool/lpd/rattan
# mkdir /var/spool/lpd/bamboo

注意:

If you are concerned about the privacy of jobs that users print, you might want to protect the spooling directory so it is not publicly accessible. Spooling directories should be owned and be readable, writable, and searchable by user daemon and group daemon, and no one else. We will do this for our example printers:

# chown daemon:daemon /var/spool/lpd/rattan
# chown daemon:daemon /var/spool/lpd/bamboo
# chmod 770 /var/spool/lpd/rattan
# chmod 770 /var/spool/lpd/bamboo

Finally, you need to tell LPD about these directories using the /etc/printcap file. You specify the pathname of the spooling directory with the sd capability:

#
#  /etc/printcap for host rose - added spooling directories
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:sd=/var/spool/lpd/rattan:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:

Note that the name of the printer starts in the first column but all other entries describing the printer should be indented and each line end escaped with a backslash.

If you do not specify a spooling directory with sd, the spooling system will use /var/spool/lpd as a default.

9.3.1.5.4. Identifying the Printer Device

In the Entries for the Ports section, we identified which entry in the /dev directory FreeBSD will use to communicate with the printer. Now, we tell LPD that information. When the spooling system has a job to print, it will open the specified device on behalf of the filter program (which is responsible for passing data to the printer).

List the /dev entry pathname in the /etc/printcap file using the lp capability.

In our running example, let us assume that rattan is on the first parallel port, and bamboo is on a sixth serial port; here are the additions to /etc/printcap:

#
#  /etc/printcap for host rose - identified what devices to use
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:sd=/var/spool/lpd/rattan:\
        :lp=/dev/lpt0:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:\
        :lp=/dev/ttyd5:

If you do not specify the lp capability for a printer in your /etc/printcap file, LPD uses /dev/lp as a default. /dev/lp currently does not exist in FreeBSD.

If the printer you are installing is connected to a parallel port, skip to the section entitled, Installing the Text Filter. Otherwise, be sure to follow the instructions in the next section.

9.3.1.5.5. Configuring Spooler Communication Parameters

For printers on serial ports, LPD can set up the bps rate, parity, and other serial communication parameters on behalf of the filter program that sends data to the printer. This is advantageous since:

  • It lets you try different communication parameters by simply editing the /etc/printcap file; you do not have to recompile the filter program.

  • It enables the spooling system to use the same filter program for multiple printers which may have different serial communication settings.

The following /etc/printcap capabilities control serial communication parameters of the device listed in the lp capability:

br#bps-rate

Sets the communications speed of the device to bps-rate, where bps-rate can be 50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200, 38400, 57600, or 115200 bits-per-second.

ms#stty-mode

Sets the options for the terminal device after opening the device. stty(1) explains the available options.

When LPD opens the device specified by the lp capability, it sets the characteristics of the device to those specified with the ms# capability. Of particular interest will be the parenb, parodd, cs5, cs6, cs7, cs8, cstopb, crtscts, and ixon modes, which are explained in the stty(1) manual page.

Let us add to our example printer on the sixth serial port. We will set the bps rate to 38400. For the mode, we will set no parity with -parenb, 8-bit characters with cs8, no modem control with clocal and hardware flow control with crtscts:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:\
        :lp=/dev/ttyd5:ms#-parenb cs8 clocal crtscts:
9.3.1.5.6. Installing the Text Filter

We are now ready to tell LPD what text filter to use to send jobs to the printer. A text filter, also known as an input filter, is a program that LPD runs when it has a job to print. When LPD runs the text filter for a printer, it sets the filter's standard input to the job to print, and its standard output to the printer device specified with the lp capability. The filter is expected to read the job from standard input, perform any necessary translation for the printer, and write the results to standard output, which will get printed. For more information on the text filter, see the Filters section.

For our simple printer setup, the text filter can be a small shell script that just executes /bin/cat to send the job to the printer. FreeBSD comes with another filter called lpf that handles backspacing and underlining for printers that might not deal with such character streams well. And, of course, you can use any other filter program you want. The filter lpf is described in detail in section entitled lpf: a Text Filter.

First, let us make the shell script /usr/local/libexec/if-simple be a simple text filter. Put the following text into that file with your favorite text editor:

#!/bin/sh
#
# if-simple - Simple text input filter for lpd
# Installed in /usr/local/libexec/if-simple
#
# Simply copies stdin to stdout.  Ignores all filter arguments.

/bin/cat && exit 0
exit 2

Make the file executable:

# chmod 555 /usr/local/libexec/if-simple

And then tell LPD to use it by specifying it with the if capability in /etc/printcap. We will add it to the two printers we have so far in the example /etc/printcap:

#
#  /etc/printcap for host rose - added text filter
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:sd=/var/spool/lpd/rattan:\ :lp=/dev/lpt0:\
        :if=/usr/local/libexec/if-simple:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:\
        :lp=/dev/ttyd5:ms#-parenb cs8 clocal crtscts:\
        :if=/usr/local/libexec/if-simple:

注意:

A copy of the if-simple script can be found in the /usr/share/examples/printing directory.

9.3.1.5.7. Turn on LPD

lpd(8) is run from /etc/rc, controlled by the lpd_enable variable. This variable defaults to NO. If you have not done so already, add the line:

lpd_enable="YES"

to /etc/rc.conf, and then either restart your machine, or just run lpd(8).

# lpd
9.3.1.5.8. Trying It Out

You have reached the end of the simple LPD setup. Unfortunately, congratulations are not quite yet in order, since we still have to test the setup and correct any problems. To test the setup, try printing something. To print with the LPD system, you use the command lpr(1), which submits a job for printing.

You can combine lpr(1) with the lptest(1) program, introduced in section Checking Printer Communications to generate some test text.

To test the simple LPD setup:

Type:

# lptest 20 5 | lpr -Pprinter-name

Where printer-name is a the name of a printer (or an alias) specified in /etc/printcap. To test the default printer, type lpr(1) without any -P argument. Again, if you are testing a printer that expects PostScript®, send a PostScript® program in that language instead of using lptest(1). You can do so by putting the program in a file and typing lpr file.

For a PostScript® printer, you should get the results of the program. If you are using lptest(1), then your results should look like the following:

!"#$%&'()*+,-./01234
"#$%&'()*+,-./012345
#$%&'()*+,-./0123456
$%&'()*+,-./01234567
%&'()*+,-./012345678

To further test the printer, try downloading larger programs (for language-based printers) or running lptest(1) with different arguments. For example, lptest 80 60 will produce 60 lines of 80 characters each.

If the printer did not work, see the Troubleshooting section.

9.4. Advanced Printer Setup

This section describes filters for printing specially formatted files, header pages, printing across networks, and restricting and accounting for printer usage.

9.4.1. Filters

Although LPD handles network protocols, queuing, access control, and other aspects of printing, most of the real work happens in the filters. Filters are programs that communicate with the printer and handle its device dependencies and special requirements. In the simple printer setup, we installed a plain text filter——an extremely simple one that should work with most printers (section Installing the Text Filter).

However, in order to take advantage of format conversion, printer accounting, specific printer quirks, and so on, you should understand how filters work. It will ultimately be the filter's responsibility to handle these aspects. And the bad news is that most of the time you have to provide filters yourself. The good news is that many are generally available; when they are not, they are usually easy to write.

Also, FreeBSD comes with one, /usr/libexec/lpr/lpf, that works with many printers that can print plain text. (It handles backspacing and tabs in the file, and does accounting, but that is about all it does.) There are also several filters and filter components in the FreeBSD Ports Collection.

Here is what you will find in this section:

  • Section How Filters Work, tries to give an overview of a filter's role in the printing process. You should read this section to get an understanding of what is happening under the hood when LPD uses filters. This knowledge could help you anticipate and debug problems you might encounter as you install more and more filters on each of your printers.

  • LPD expects every printer to be able to print plain text by default. This presents a problem for PostScript® (or other language-based printers) which cannot directly print plain text. Section Accommodating Plain Text Jobs on PostScript® Printers tells you what you should do to overcome this problem. You should read this section if you have a PostScript® printer.

  • PostScript® is a popular output format for many programs. Some people even write PostScript® code directly. Unfortunately, PostScript® printers are expensive. Section Simulating PostScript® on Non PostScript® Printers tells how you can further modify a printer's text filter to accept and print PostScript® data on a non PostScript® printer. You should read this section if you do not have a PostScript® printer.

  • Section Conversion Filters tells about a way you can automate the conversion of specific file formats, such as graphic or typesetting data, into formats your printer can understand. After reading this section, you should be able to set up your printers such that users can type lpr -t to print troff data, or lpr -d to print TeX DVI data, or lpr -v to print raster image data, and so forth. I recommend reading this section.

  • Section Output Filters tells all about a not often used feature of LPD: output filters. Unless you are printing header pages (see Header Pages), you can probably skip that section altogether.

  • Section lpf: a Text Filter describes lpf, a fairly complete if simple text filter for line printers (and laser printers that act like line printers) that comes with FreeBSD. If you need a quick way to get printer accounting working for plain text, or if you have a printer which emits smoke when it sees backspace characters, you should definitely consider lpf.

注意:

A copy of the various scripts described below can be found in the /usr/share/examples/printing directory.

9.4.1.1. How Filters Work

As mentioned before, a filter is an executable program started by LPD to handle the device-dependent part of communicating with the printer.

When LPD wants to print a file in a job, it starts a filter program. It sets the filter's standard input to the file to print, its standard output to the printer, and its standard error to the error logging file (specified in the lf capability in /etc/printcap, or /dev/console by default).

Which filter LPD starts and the filter's arguments depend on what is listed in the /etc/printcap file and what arguments the user specified for the job on the lpr(1) command line. For example, if the user typed lpr -t, LPD would start the troff filter, listed in the tf capability for the destination printer. If the user wanted to print plain text, it would start the if filter (this is mostly true: see Output Filters for details).

There are three kinds of filters you can specify in /etc/printcap:

  • The text filter, confusingly called the input filter in LPD documentation, handles regular text printing. Think of it as the default filter. LPD expects every printer to be able to print plain text by default, and it is the text filter's job to make sure backspaces, tabs, or other special characters do not confuse the printer. If you are in an environment where you have to account for printer usage, the text filter must also account for pages printed, usually by counting the number of lines printed and comparing that to the number of lines per page the printer supports. The text filter is started with the following argument list:

    filter-name [-c] -wwidth -llength -iindent -n login -h host acct-file

    where

    -c

    appears if the job is submitted with lpr -l

    width

    is the value from the pw (page width) capability specified in /etc/printcap, default 132

    length

    is the value from the pl (page length) capability, default 66

    indent

    is the amount of the indentation from lpr -i, default 0

    login

    is the account name of the user printing the file

    host

    is the host name from which the job was submitted

    acct-file

    is the name of the accounting file from the af capability.

  • A conversion filter converts a specific file format into one the printer can render onto paper. For example, ditroff typesetting data cannot be directly printed, but you can install a conversion filter for ditroff files to convert the ditroff data into a form the printer can digest and print. Section Conversion Filters tells all about them. Conversion filters also need to do accounting, if you need printer accounting. Conversion filters are started with the following arguments:

    filter-name -xpixel-width -ypixel-height -n login -h host acct-file

    where pixel-width is the value from the px capability (default 0) and pixel-height is the value from the py capability (default 0).

  • The output filter is used only if there is no text filter, or if header pages are enabled. In my experience, output filters are rarely used. Section Output Filters describe them. There are only two arguments to an output filter:

    filter-name -wwidth -llength

    which are identical to the text filters -w and -l arguments.

Filters should also exit with the following exit status:

exit 0

If the filter printed the file successfully.

exit 1

If the filter failed to print the file but wants LPD to try to print the file again. LPD will restart a filter if it exits with this status.

exit 2

If the filter failed to print the file and does not want LPD to try again. LPD will throw out the file.

The text filter that comes with the FreeBSD release, /usr/libexec/lpr/lpf, takes advantage of the page width and length arguments to determine when to send a form feed and how to account for printer usage. It uses the login, host, and accounting file arguments to make the accounting entries.

If you are shopping for filters, see if they are LPD-compatible. If they are, they must support the argument lists described above. If you plan on writing filters for general use, then have them support the same argument lists and exit codes.

9.4.1.2. Accommodating Plain Text Jobs on PostScript® Printers

If you are the only user of your computer and PostScript® (or other language-based) printer, and you promise to never send plain text to your printer and to never use features of various programs that will want to send plain text to your printer, then you do not need to worry about this section at all.

But, if you would like to send both PostScript® and plain text jobs to the printer, then you are urged to augment your printer setup. To do so, we have the text filter detect if the arriving job is plain text or PostScript®. All PostScript® jobs must start with %! (for other printer languages, see your printer documentation). If those are the first two characters in the job, we have PostScript®, and can pass the rest of the job directly. If those are not the first two characters in the file, then the filter will convert the text into PostScript® and print the result.

How do we do this?

If you have got a serial printer, a great way to do it is to install lprps. lprps is a PostScript® printer filter which performs two-way communication with the printer. It updates the printer's status file with verbose information from the printer, so users and administrators can see exactly what the state of the printer is (such as toner low or paper jam). But more importantly, it includes a program called psif which detects whether the incoming job is plain text and calls textps (another program that comes with lprps) to convert it to PostScript®. It then uses lprps to send the job to the printer.

lprps is part of the FreeBSD Ports Collection (see The Ports Collection). You can fetch, build and install it yourself, of course. After installing lprps, just specify the pathname to the psif program that is part of lprps. If you installed lprps from the Ports Collection, use the following in the serial PostScript® printer's entry in /etc/printcap:

:if=/usr/local/libexec/psif:

You should also specify the rw capability; that tells LPD to open the printer in read-write mode.

If you have a parallel PostScript® printer (and therefore cannot use two-way communication with the printer, which lprps needs), you can use the following shell script as the text filter:

#!/bin/sh
#
#  psif - Print PostScript or plain text on a PostScript printer
#  Script version; NOT the version that comes with lprps
#  Installed in /usr/local/libexec/psif
#

IFS="" read -r first_line
first_two_chars=`expr "$first_line" : '\(..\)'`

if [ "$first_two_chars" = "%!" ]; then
    #
    #  PostScript job, print it.
    #
    echo "$first_line" && cat && printf "\004" && exit 0
    exit 2
else
    #
    #  Plain text, convert it, then print it.
    #
    ( echo "$first_line"; cat ) | /usr/local/bin/textps && printf "\004" && exit 0
    exit 2
fi

In the above script, textps is a program we installed separately to convert plain text to PostScript®. You can use any text-to-PostScript® program you wish. The FreeBSD Ports Collection (see The Ports Collection) includes a full featured text-to-PostScript® program called a2ps that you might want to investigate.

9.4.1.3. Simulating PostScript® on Non PostScript® Printers

PostScript® is the de facto standard for high quality typesetting and printing. PostScript® is, however, an expensive standard. Thankfully, Aladdin Enterprises has a free PostScript® work-alike called Ghostscript that runs with FreeBSD. Ghostscript can read most PostScript® files and can render their pages onto a variety of devices, including many brands of non-PostScript printers. By installing Ghostscript and using a special text filter for your printer, you can make your non PostScript® printer act like a real PostScript® printer.

Ghostscript is in the FreeBSD Ports Collection, if you would like to install it from there. You can fetch, build, and install it quite easily yourself, as well.

To simulate PostScript®, we have the text filter detect if it is printing a PostScript® file. If it is not, then the filter will pass the file directly to the printer; otherwise, it will use Ghostscript to first convert the file into a format the printer will understand.

Here is an example: the following script is a text filter for Hewlett Packard DeskJet 500 printers. For other printers, substitute the -sDEVICE argument to the gs (Ghostscript) command. (Type gs -h to get a list of devices the current installation of Ghostscript supports.)

#!/bin/sh
#
#  ifhp - Print Ghostscript-simulated PostScript on a DeskJet 500
#  Installed in /usr/local/libexec/ifhp

#
#  Treat LF as CR+LF (to avoid the "staircase effect" on HP/PCL
#  printers):
#
printf "\033&k2G" || exit 2

#
#  Read first two characters of the file
#
IFS="" read -r first_line
first_two_chars=`expr "$first_line" : '\(..\)'`

if [ "$first_two_chars" = "%!" ]; then
    #
    #  It is PostScript; use Ghostscript to scan-convert and print it.
    #
    /usr/local/bin/gs -dSAFER -dNOPAUSE -q -sDEVICE=djet500 \
      -sOutputFile=- - && exit 0
else
    #
    #  Plain text or HP/PCL, so just print it directly; print a form feed
    #  at the end to eject the last page.
    #
    echo "$first_line" && cat && printf "\033&l0H" &&
exit 0
fi

exit 2

Finally, you need to notify LPD of the filter via the if capability:

:if=/usr/local/libexec/ifhp:

That is it. You can type lpr plain.text and lpr whatever.ps and both should print successfully.

9.4.1.4. Conversion Filters

After completing the simple setup described in Simple Printer Setup, the first thing you will probably want to do is install conversion filters for your favorite file formats (besides plain ASCII text).

9.4.1.4.1. Why Install Conversion Filters?

Conversion filters make printing various kinds of files easy. As an example, suppose we do a lot of work with the TeX typesetting system, and we have a PostScript® printer. Every time we generate a DVI file from TeX, we cannot print it directly until we convert the DVI file into PostScript®. The command sequence goes like this:

% dvips seaweed-analysis.dvi
% lpr seaweed-analysis.ps

By installing a conversion filter for DVI files, we can skip the hand conversion step each time by having LPD do it for us. Now, each time we get a DVI file, we are just one step away from printing it:

% lpr -d seaweed-analysis.dvi

We got LPD to do the DVI file conversion for us by specifying the -d option. Section Formatting and Conversion Options lists the conversion options.

For each of the conversion options you want a printer to support, install a conversion filter and specify its pathname in /etc/printcap. A conversion filter is like the text filter for the simple printer setup (see section Installing the Text Filter) except that instead of printing plain text, the filter converts the file into a format the printer can understand.

9.4.1.4.2. Which Conversion Filters Should I Install?

You should install the conversion filters you expect to use. If you print a lot of DVI data, then a DVI conversion filter is in order. If you have got plenty of troff to print out, then you probably want a troff filter.

The following table summarizes the filters that LPD works with, their capability entries for the /etc/printcap file, and how to invoke them with the lpr command:

File type/etc/printcap capabilitylpr option
cifplotcf-c
DVIdf-d
plotgf-g
ditroffnf-n
FORTRAN textrf-f
trofftf-f
rastervf-v
plain textifnone, -p, or -l

In our example, using lpr -d means the printer needs a df capability in its entry in /etc/printcap.

Despite what others might contend, formats like FORTRAN text and plot are probably obsolete. At your site, you can give new meanings to these or any of the formatting options just by installing custom filters. For example, suppose you would like to directly print Printerleaf files (files from the Interleaf desktop publishing program), but will never print plot files. You could install a Printerleaf conversion filter under the gf capability and then educate your users that lpr -g mean print Printerleaf files.

9.4.1.4.3. Installing Conversion Filters

Since conversion filters are programs you install outside of the base FreeBSD installation, they should probably go under /usr/local. The directory /usr/local/libexec is a popular location, since they are specialized programs that only LPD will run; regular users should not ever need to run them.

To enable a conversion filter, specify its pathname under the appropriate capability for the destination printer in /etc/printcap.

In our example, we will add the DVI conversion filter to the entry for the printer named bamboo. Here is the example /etc/printcap file again, with the new df capability for the printer bamboo.

#
#  /etc/printcap for host rose - added df filter for bamboo
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:sd=/var/spool/lpd/rattan:\
        :lp=/dev/lpt0:\
        :if=/usr/local/libexec/if-simple:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:\
        :lp=/dev/ttyd5:ms#-parenb cs8 clocal crtscts:rw:\
        :if=/usr/local/libexec/psif:\
        :df=/usr/local/libexec/psdf:

The DVI filter is a shell script named /usr/local/libexec/psdf. Here is that script:

#!/bin/sh
#
#  psdf - DVI to PostScript printer filter
#  Installed in /usr/local/libexec/psdf
#
# Invoked by lpd when user runs lpr -d
#
exec /usr/local/bin/dvips -f | /usr/local/libexec/lprps "$@"

This script runs dvips in filter mode (the -f argument) on standard input, which is the job to print. It then starts the PostScript® printer filter lprps (see section Accommodating Plain Text Jobs on PostScript® Printers) with the arguments LPD passed to this script. lprps will use those arguments to account for the pages printed.

9.4.1.4.4. More Conversion Filter Examples

Since there is no fixed set of steps to install conversion filters, let me instead provide more examples. Use these as guidance to making your own filters. Use them directly, if appropriate.

This example script is a raster (well, GIF file, actually) conversion filter for a Hewlett Packard LaserJet III-Si printer:

#!/bin/sh
#
#  hpvf - Convert GIF files into HP/PCL, then print
#  Installed in /usr/local/libexec/hpvf

PATH=/usr/X11R6/bin:$PATH; export PATH
giftopnm | ppmtopgm | pgmtopbm | pbmtolj -resolution 300 \
    && exit 0 \
    || exit 2

It works by converting the GIF file into a portable anymap, converting that into a portable graymap, converting that into a portable bitmap, and converting that into LaserJet/PCL-compatible data.

Here is the /etc/printcap file with an entry for a printer using the above filter:

#
#  /etc/printcap for host orchid
#
teak|hp|laserjet|Hewlett Packard LaserJet 3Si:\
        :lp=/dev/lpt0:sh:sd=/var/spool/lpd/teak:mx#0:\
        :if=/usr/local/libexec/hpif:\
        :vf=/usr/local/libexec/hpvf:

The following script is a conversion filter for troff data from the groff typesetting system for the PostScript® printer named bamboo:

#!/bin/sh
#
#  pstf - Convert groff's troff data into PS, then print.
#  Installed in /usr/local/libexec/pstf
#
exec grops | /usr/local/libexec/lprps "$@"

The above script makes use of lprps again to handle the communication with the printer. If the printer were on a parallel port, we would use this script instead:

#!/bin/sh
#
#  pstf - Convert groff's troff data into PS, then print.
#  Installed in /usr/local/libexec/pstf
#
exec grops

That is it. Here is the entry we need to add to /etc/printcap to enable the filter:

:tf=/usr/local/libexec/pstf:

Here is an example that might make old hands at FORTRAN blush. It is a FORTRAN-text filter for any printer that can directly print plain text. We will install it for the printer teak:

#!/bin/sh
#
# hprf - FORTRAN text filter for LaserJet 3si:
# Installed in /usr/local/libexec/hprf
#

printf "\033&k2G" && fpr && printf "\033&l0H" &&
 exit 0
exit 2

And we will add this line to the /etc/printcap for the printer teak to enable this filter:

:rf=/usr/local/libexec/hprf:

Here is one final, somewhat complex example. We will add a DVI filter to the LaserJet printer teak introduced earlier. First, the easy part: updating /etc/printcap with the location of the DVI filter:

:df=/usr/local/libexec/hpdf:

Now, for the hard part: making the filter. For that, we need a DVI-to-LaserJet/PCL conversion program. The FreeBSD Ports Collection (see The Ports Collection) has one: dvi2xx is the name of the package. Installing this package gives us the program we need, dvilj2p, which converts DVI into LaserJet IIp, LaserJet III, and LaserJet 2000 compatible codes.

dvilj2p makes the filter hpdf quite complex since dvilj2p cannot read from standard input. It wants to work with a filename. What is worse, the filename has to end in .dvi so using /dev/fd/0 for standard input is problematic. We can get around that problem by linking (symbolically) a temporary file name (one that ends in .dvi) to /dev/fd/0, thereby forcing dvilj2p to read from standard input.

The only other fly in the ointment is the fact that we cannot use /tmp for the temporary link. Symbolic links are owned by user and group bin. The filter runs as user daemon. And the /tmp directory has the sticky bit set. The filter can create the link, but it will not be able clean up when done and remove it since the link will belong to a different user.

Instead, the filter will make the symbolic link in the current working directory, which is the spooling directory (specified by the sd capability in /etc/printcap). This is a perfect place for filters to do their work, especially since there is (sometimes) more free disk space in the spooling directory than under /tmp.

Here, finally, is the filter:

#!/bin/sh
#
#  hpdf - Print DVI data on HP/PCL printer
#  Installed in /usr/local/libexec/hpdf

PATH=/usr/local/bin:$PATH; export PATH

#
#  Define a function to clean up our temporary files.  These exist
#  in the current directory, which will be the spooling directory
#  for the printer.
#
cleanup() {
   rm -f hpdf$$.dvi
}

#
#  Define a function to handle fatal errors: print the given message
#  and exit 2.  Exiting with 2 tells LPD to do not try to reprint the
#  job.
#
fatal() {
    echo "$@" 1>&2
    cleanup
    exit 2
}

#
#  If user removes the job, LPD will send SIGINT, so trap SIGINT
#  (and a few other signals) to clean up after ourselves.
#
trap cleanup 1 2 15

#
#  Make sure we are not colliding with any existing files.
#
cleanup

#
#  Link the DVI input file to standard input (the file to print).
#
ln -s /dev/fd/0 hpdf$$.dvi || fatal "Cannot symlink /dev/fd/0"

#
#  Make LF = CR+LF
#
printf "\033&k2G" || fatal "Cannot initialize printer"

#
#  Convert and print.  Return value from dvilj2p does not seem to be
#  reliable, so we ignore it.
#
dvilj2p -M1 -q -e- dfhp$$.dvi

#
#  Clean up and exit
#
cleanup
exit 0
9.4.1.4.5. Automated Conversion: an Alternative to Conversion Filters

All these conversion filters accomplish a lot for your printing environment, but at the cost forcing the user to specify (on the lpr(1) command line) which one to use. If your users are not particularly computer literate, having to specify a filter option will become annoying. What is worse, though, is that an incorrectly specified filter option may run a filter on the wrong type of file and cause your printer to spew out hundreds of sheets of paper.

Rather than install conversion filters at all, you might want to try having the text filter (since it is the default filter) detect the type of file it has been asked to print and then automatically run the right conversion filter. Tools such as file can be of help here. Of course, it will be hard to determine the differences between some file types——and, of course, you can still provide conversion filters just for them.

The FreeBSD Ports Collection has a text filter that performs automatic conversion called apsfilter. It can detect plain text, PostScript®, and DVI files, run the proper conversions, and print.

9.4.1.5. Output Filters

The LPD spooling system supports one other type of filter that we have not yet explored: an output filter. An output filter is intended for printing plain text only, like the text filter, but with many simplifications. If you are using an output filter but no text filter, then:

  • LPD starts an output filter once for the entire job instead of once for each file in the job.

  • LPD does not make any provision to identify the start or the end of files within the job for the output filter.

  • LPD does not pass the user's login or host to the filter, so it is not intended to do accounting. In fact, it gets only two arguments:

    filter-name -wwidth -llength

    Where width is from the pw capability and length is from the pl capability for the printer in question.

Do not be seduced by an output filter's simplicity. If you would like each file in a job to start on a different page an output filter will not work. Use a text filter (also known as an input filter); see section Installing the Text Filter. Furthermore, an output filter is actually more complex in that it has to examine the byte stream being sent to it for special flag characters and must send signals to itself on behalf of LPD.

However, an output filter is necessary if you want header pages and need to send escape sequences or other initialization strings to be able to print the header page. (But it is also futile if you want to charge header pages to the requesting user's account, since LPD does not give any user or host information to the output filter.)

On a single printer, LPD allows both an output filter and text or other filters. In such cases, LPD will start the output filter to print the header page (see section Header Pages) only. LPD then expects the output filter to stop itself by sending two bytes to the filter: ASCII 031 followed by ASCII 001. When an output filter sees these two bytes (031, 001), it should stop by sending SIGSTOP to itself. When LPD's done running other filters, it will restart the output filter by sending SIGCONT to it.

If there is an output filter but no text filter and LPD is working on a plain text job, LPD uses the output filter to do the job. As stated before, the output filter will print each file of the job in sequence with no intervening form feeds or other paper advancement, and this is probably not what you want. In almost all cases, you need a text filter.

The program lpf, which we introduced earlier as a text filter, can also run as an output filter. If you need a quick-and-dirty output filter but do not want to write the byte detection and signal sending code, try lpf. You can also wrap lpf in a shell script to handle any initialization codes the printer might require.

9.4.1.6. lpf: a Text Filter

The program /usr/libexec/lpr/lpf that comes with FreeBSD binary distribution is a text filter (input filter) that can indent output (job submitted with lpr -i), allow literal characters to pass (job submitted with lpr -l), adjust the printing position for backspaces and tabs in the job, and account for pages printed. It can also act like an output filter.

lpf is suitable for many printing environments. And although it has no capability to send initialization sequences to a printer, it is easy to write a shell script to do the needed initialization and then execute lpf.

In order for lpf to do page accounting correctly, it needs correct values filled in for the pw and pl capabilities in the /etc/printcap file. It uses these values to determine how much text can fit on a page and how many pages were in a user's job. For more information on printer accounting, see Accounting for Printer Usage.

9.4.2. Header Pages

If you have lots of users, all of them using various printers, then you probably want to consider header pages as a necessary evil.

Header pages, also known as banner or burst pages identify to whom jobs belong after they are printed. They are usually printed in large, bold letters, perhaps with decorative borders, so that in a stack of printouts they stand out from the real documents that comprise users' jobs. They enable users to locate their jobs quickly. The obvious drawback to a header page is that it is yet one more sheet that has to be printed for every job, their ephemeral usefulness lasting not more than a few minutes, ultimately finding themselves in a recycling bin or rubbish heap. (Note that header pages go with each job, not each file in a job, so the paper waste might not be that bad.)

The LPD system can provide header pages automatically for your printouts if your printer can directly print plain text. If you have a PostScript® printer, you will need an external program to generate the header page; see Header Pages on PostScript® Printers.

9.4.2.1. Enabling Header Pages

In the Simple Printer Setup section, we turned off header pages by specifying sh (meaning suppress header) in the /etc/printcap file. To enable header pages for a printer, just remove the sh capability.

Sounds too easy, right?

You are right. You might have to provide an output filter to send initialization strings to the printer. Here is an example output filter for Hewlett Packard PCL-compatible printers:

#!/bin/sh
#
#  hpof - Output filter for Hewlett Packard PCL-compatible printers
#  Installed in /usr/local/libexec/hpof

printf "\033&k2G" || exit 2
exec /usr/libexec/lpr/lpf

Specify the path to the output filter in the of capability. See the Output Filters section for more information.

Here is an example /etc/printcap file for the printer teak that we introduced earlier; we enabled header pages and added the above output filter:

#
#  /etc/printcap for host orchid
#
teak|hp|laserjet|Hewlett Packard LaserJet 3Si:\
        :lp=/dev/lpt0:sd=/var/spool/lpd/teak:mx#0:\
        :if=/usr/local/libexec/hpif:\
        :vf=/usr/local/libexec/hpvf:\
        :of=/usr/local/libexec/hpof:

Now, when users print jobs to teak, they get a header page with each job. If users want to spend time searching for their printouts, they can suppress header pages by submitting the job with lpr -h; see the Header Page Options section for more lpr(1) options.

注意:

LPD prints a form feed character after the header page. If your printer uses a different character or sequence of characters to eject a page, specify them with the ff capability in /etc/printcap.

9.4.2.2. Controlling Header Pages

By enabling header pages, LPD will produce a long header, a full page of large letters identifying the user, host, and job. Here is an example (kelly printed the job named outline from host rose):

      k                   ll       ll
      k                    l        l
      k                    l        l
      k   k     eeee       l        l     y    y
      k  k     e    e      l        l     y    y
      k k      eeeeee      l        l     y    y
      kk k     e           l        l     y    y
      k   k    e    e      l        l     y   yy
      k    k    eeee      lll      lll     yyy y
                                               y
                                          y    y
                                           yyyy


                                   ll
                          t         l        i
                          t         l
       oooo    u    u   ttttt       l       ii     n nnn     eeee
      o    o   u    u     t         l        i     nn   n   e    e
      o    o   u    u     t         l        i     n    n   eeeeee
      o    o   u    u     t         l        i     n    n   e
      o    o   u   uu     t  t      l        i     n    n   e    e
       oooo     uuu u      tt      lll      iii    n    n    eeee









      r rrr     oooo     ssss     eeee
      rr   r   o    o   s    s   e    e
      r        o    o    ss      eeeeee
      r        o    o      ss    e
      r        o    o   s    s   e    e
      r         oooo     ssss     eeee







                                              Job:  outline
                                              Date: Sun Sep 17 11:04:58 1995

LPD appends a form feed after this text so the job starts on a new page (unless you have sf (suppress form feeds) in the destination printer's entry in /etc/printcap).

If you prefer, LPD can make a short header; specify sb (short banner) in the /etc/printcap file. The header page will look like this:

rose:kelly  Job: outline  Date: Sun Sep 17 11:07:51 1995

Also by default, LPD prints the header page first, then the job. To reverse that, specify hl (header last) in /etc/printcap.

9.4.2.3. Accounting for Header Pages

Using LPD's built-in header pages enforces a particular paradigm when it comes to printer accounting: header pages must be free of charge.

Why?

Because the output filter is the only external program that will have control when the header page is printed that could do accounting, and it is not provided with any user or host information or an accounting file, so it has no idea whom to charge for printer use. It is also not enough to just add one page to the text filter or any of the conversion filters (which do have user and host information) since users can suppress header pages with lpr -h. They could still be charged for header pages they did not print. Basically, lpr -h will be the preferred option of environmentally-minded users, but you cannot offer any incentive to use it.

It is still not enough to have each of the filters generate their own header pages (thereby being able to charge for them). If users wanted the option of suppressing the header pages with lpr -h, they will still get them and be charged for them since LPD does not pass any knowledge of the -h option to any of the filters.

So, what are your options?

You can:

  • Accept LPD's paradigm and make header pages free.

  • Install an alternative to LPD, such as LPRng. Section Alternatives to the Standard Spooler tells more about other spooling software you can substitute for LPD.

  • Write a smart output filter. Normally, an output filter is not meant to do anything more than initialize a printer or do some simple character conversion. It is suited for header pages and plain text jobs (when there is no text (input) filter). But, if there is a text filter for the plain text jobs, then LPD will start the output filter only for the header pages. And the output filter can parse the header page text that LPD generates to determine what user and host to charge for the header page. The only other problem with this method is that the output filter still does not know what accounting file to use (it is not passed the name of the file from the af capability), but if you have a well-known accounting file, you can hard-code that into the output filter. To facilitate the parsing step, use the sh (short header) capability in /etc/printcap. Then again, all that might be too much trouble, and users will certainly appreciate the more generous system administrator who makes header pages free.

9.4.2.4. Header Pages on PostScript® Printers

As described above, LPD can generate a plain text header page suitable for many printers. Of course, PostScript® cannot directly print plain text, so the header page feature of LPD is useless——or mostly so.

One obvious way to get header pages is to have every conversion filter and the text filter generate the header page. The filters should use the user and host arguments to generate a suitable header page. The drawback of this method is that users will always get a header page, even if they submit jobs with lpr -h.

Let us explore this method. The following script takes three arguments (user login name, host name, and job name) and makes a simple PostScript® header page:

#!/bin/sh
#
#  make-ps-header - make a PostScript header page on stdout
#  Installed in /usr/local/libexec/make-ps-header
#

#
#  These are PostScript units (72 to the inch).  Modify for A4 or
#  whatever size paper you are using:
#
page_width=612
page_height=792
border=72

#
#  Check arguments
#
if [ $# -ne 3 ]; then
    echo "Usage: `basename $0` <user> <host> <job>" 1>&2
    exit 1
fi

#
#  Save these, mostly for readability in the PostScript, below.
#
user=$1
host=$2
job=$3
date=`date`

#
#  Send the PostScript code to stdout.
#
exec cat <<EOF
%!PS

%
%  Make sure we do not interfere with user's job that will follow
%
save

%
%  Make a thick, unpleasant border around the edge of the paper.
%
$border $border moveto
$page_width $border 2 mul sub 0 rlineto
0 $page_height $border 2 mul sub rlineto
currentscreen 3 -1 roll pop 100 3 1 roll setscreen
$border 2 mul $page_width sub 0 rlineto closepath
0.8 setgray 10 setlinewidth stroke 0 setgray

%
%  Display user's login name, nice and large and prominent
%
/Helvetica-Bold findfont 64 scalefont setfont
$page_width ($user) stringwidth pop sub 2 div $page_height 200 sub moveto
($user) show

%
%  Now show the boring particulars
%
/Helvetica findfont 14 scalefont setfont
/y 200 def
[ (Job:) (Host:) (Date:) ] {
200 y moveto show /y y 18 sub def }
forall

/Helvetica-Bold findfont 14 scalefont setfont
/y 200 def
[ ($job) ($host) ($date) ] {
        270 y moveto show /y y 18 sub def
} forall

%
% That is it
%
restore
showpage
EOF

Now, each of the conversion filters and the text filter can call this script to first generate the header page, and then print the user's job. Here is the DVI conversion filter from earlier in this document, modified to make a header page:

#!/bin/sh
#
#  psdf - DVI to PostScript printer filter
#  Installed in /usr/local/libexec/psdf
#
#  Invoked by lpd when user runs lpr -d
#

orig_args="$@"

fail() {
    echo "$@" 1>&2
    exit 2
}

while getopts "x:y:n:h:" option; do
    case $option in
        x|y)  ;; # Ignore
        n)    login=$OPTARG ;;
        h)    host=$OPTARG ;;
        *)    echo "LPD started `basename $0` wrong." 1>&2
              exit 2
              ;;
    esac
done

[ "$login" ] || fail "No login name"
[ "$host" ] || fail "No host name"

( /usr/local/libexec/make-ps-header $login $host "DVI File"
  /usr/local/bin/dvips -f ) | eval /usr/local/libexec/lprps $orig_args

Notice how the filter has to parse the argument list in order to determine the user and host name. The parsing for the other conversion filters is identical. The text filter takes a slightly different set of arguments, though (see section How Filters Work).

As we have mentioned before, the above scheme, though fairly simple, disables the suppress header page option (the -h option) to lpr. If users wanted to save a tree (or a few pennies, if you charge for header pages), they would not be able to do so, since every filter's going to print a header page with every job.

To allow users to shut off header pages on a per-job basis, you will need to use the trick introduced in section Accounting for Header Pages: write an output filter that parses the LPD-generated header page and produces a PostScript® version. If the user submits the job with lpr -h, then LPD will not generate a header page, and neither will your output filter. Otherwise, your output filter will read the text from LPD and send the appropriate header page PostScript® code to the printer.

If you have a PostScript® printer on a serial line, you can make use of lprps, which comes with an output filter, psof, which does the above. Note that psof does not charge for header pages.

9.4.3. Networked Printing

FreeBSD supports networked printing: sending jobs to remote printers. Networked printing generally refers to two different things:

  • Accessing a printer attached to a remote host. You install a printer that has a conventional serial or parallel interface on one host. Then, you set up LPD to enable access to the printer from other hosts on the network. Section Printers Installed on Remote Hosts tells how to do this.

  • Accessing a printer attached directly to a network. The printer has a network interface in addition (or in place of) a more conventional serial or parallel interface. Such a printer might work as follows:

    • It might understand the LPD protocol and can even queue jobs from remote hosts. In this case, it acts just like a regular host running LPD. Follow the same procedure in section Printers Installed on Remote Hosts to set up such a printer.

    • It might support a data stream network connection. In this case, you attach the printer to one host on the network by making that host responsible for spooling jobs and sending them to the printer. Section Printers with Networked Data Stream Interfaces gives some suggestions on installing such printers.

9.4.3.1. Printers Installed on Remote Hosts

The LPD spooling system has built-in support for sending jobs to other hosts also running LPD (or are compatible with LPD). This feature enables you to install a printer on one host and make it accessible from other hosts. It also works with printers that have network interfaces that understand the LPD protocol.

To enable this kind of remote printing, first install a printer on one host, the printer host, using the simple printer setup described in the Simple Printer Setup section. Do any advanced setup in Advanced Printer Setup that you need. Make sure to test the printer and see if it works with the features of LPD you have enabled. Also ensure that the local host has authorization to use the LPD service in the remote host (see Restricting Jobs from Remote Printers).

If you are using a printer with a network interface that is compatible with LPD, then the printer host in the discussion below is the printer itself, and the printer name is the name you configured for the printer. See the documentation that accompanied your printer and/or printer-network interface.

提示:

If you are using a Hewlett Packard Laserjet then the printer name text will automatically perform the LF to CRLF conversion for you, so you will not require the hpif script.

Then, on the other hosts you want to have access to the printer, make an entry in their /etc/printcap files with the following:

  1. Name the entry anything you want. For simplicity, though, you probably want to use the same name and aliases as on the printer host.

  2. Leave the lp capability blank, explicitly (:lp=:).

  3. Make a spooling directory and specify its location in the sd capability. LPD will store jobs here before they get sent to the printer host.

  4. Place the name of the printer host in the rm capability.

  5. Place the printer name on the printer host in the rp capability.

That is it. You do not need to list conversion filters, page dimensions, or anything else in the /etc/printcap file.

Here is an example. The host rose has two printers, bamboo and rattan. We will enable users on the host orchid to print to those printers. Here is the /etc/printcap file for orchid (back from section Enabling Header Pages). It already had the entry for the printer teak; we have added entries for the two printers on the host rose:

#
#  /etc/printcap for host orchid - added (remote) printers on rose
#

#
#  teak is local; it is connected directly to orchid:
#
teak|hp|laserjet|Hewlett Packard LaserJet 3Si:\
        :lp=/dev/lpt0:sd=/var/spool/lpd/teak:mx#0:\
        :if=/usr/local/libexec/ifhp:\
        :vf=/usr/local/libexec/vfhp:\
        :of=/usr/local/libexec/ofhp:

#
#  rattan is connected to rose; send jobs for rattan to rose:
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :lp=:rm=rose:rp=rattan:sd=/var/spool/lpd/rattan:

#
#  bamboo is connected to rose as well:
#
bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :lp=:rm=rose:rp=bamboo:sd=/var/spool/lpd/bamboo:

Then, we just need to make spooling directories on orchid:

# mkdir -p /var/spool/lpd/rattan /var/spool/lpd/bamboo
# chmod 770 /var/spool/lpd/rattan /var/spool/lpd/bamboo
# chown daemon:daemon /var/spool/lpd/rattan /var/spool/lpd/bamboo

Now, users on orchid can print to rattan and bamboo. If, for example, a user on orchid typed

% lpr -P bamboo -d sushi-review.dvi

the LPD system on orchid would copy the job to the spooling directory /var/spool/lpd/bamboo and note that it was a DVI job. As soon as the host rose has room in its bamboo spooling directory, the two LPDs would transfer the file to rose. The file would wait in rose's queue until it was finally printed. It would be converted from DVI to PostScript® (since bamboo is a PostScript® printer) on rose.

9.4.3.2. Printers with Networked Data Stream Interfaces

Often, when you buy a network interface card for a printer, you can get two versions: one which emulates a spooler (the more expensive version), or one which just lets you send data to it as if you were using a serial or parallel port (the cheaper version). This section tells how to use the cheaper version. For the more expensive one, see the previous section Printers Installed on Remote Hosts.

The format of the /etc/printcap file lets you specify what serial or parallel interface to use, and (if you are using a serial interface), what baud rate, whether to use flow control, delays for tabs, conversion of newlines, and more. But there is no way to specify a connection to a printer that is listening on a TCP/IP or other network port.

To send data to a networked printer, you need to develop a communications program that can be called by the text and conversion filters. Here is one such example: the script netprint takes all data on standard input and sends it to a network-attached printer. We specify the hostname of the printer as the first argument and the port number to which to connect as the second argument to netprint. Note that this supports one-way communication only (FreeBSD to printer); many network printers support two-way communication, and you might want to take advantage of that (to get printer status, perform accounting, etc.).

#!/usr/bin/perl
#
#  netprint - Text filter for printer attached to network
#  Installed in /usr/local/libexec/netprint
#
$#ARGV eq 1 || die "Usage: $0 <printer-hostname> <port-number>";

$printer_host = $ARGV[0];
$printer_port = $ARGV[1];

require 'sys/socket.ph';

($ignore, $ignore, $protocol) = getprotobyname('tcp');
($ignore, $ignore, $ignore, $ignore, $address)
    = gethostbyname($printer_host);

$sockaddr = pack('S n a4 x8', &AF_INET, $printer_port, $address);

socket(PRINTER, &PF_INET, &SOCK_STREAM, $protocol)
    || die "Can't create TCP/IP stream socket: $!";
connect(PRINTER, $sockaddr) || die "Can't contact $printer_host: $!";
while (<STDIN>) { print PRINTER; }
exit 0;

We can then use this script in various filters. Suppose we had a Diablo 750-N line printer connected to the network. The printer accepts data to print on port number 5100. The host name of the printer is scrivener. Here is the text filter for the printer:

#!/bin/sh
#
#  diablo-if-net - Text filter for Diablo printer `scrivener' listening
#  on port 5100.   Installed in /usr/local/libexec/diablo-if-net
#
exec /usr/libexec/lpr/lpf "$@" | /usr/local/libexec/netprint scrivener 5100

9.4.4. Restricting Printer Usage

This section gives information on restricting printer usage. The LPD system lets you control who can access a printer, both locally or remotely, whether they can print multiple copies, how large their jobs can be, and how large the printer queues can get.

9.4.4.1. Restricting Multiple Copies

The LPD system makes it easy for users to print multiple copies of a file. Users can print jobs with lpr -#5 (for example) and get five copies of each file in the job. Whether this is a good thing is up to you.

If you feel multiple copies cause unnecessary wear and tear on your printers, you can disable the -# option to lpr(1) by adding the sc capability to the /etc/printcap file. When users submit jobs with the -# option, they will see:

lpr: multiple copies are not allowed

Note that if you have set up access to a printer remotely (see section Printers Installed on Remote Hosts), you need the sc capability on the remote /etc/printcap files as well, or else users will still be able to submit multiple-copy jobs by using another host.

Here is an example. This is the /etc/printcap file for the host rose. The printer rattan is quite hearty, so we will allow multiple copies, but the laser printer bamboo is a bit more delicate, so we will disable multiple copies by adding the sc capability:

#
#  /etc/printcap for host rose - restrict multiple copies on bamboo
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:sd=/var/spool/lpd/rattan:\
        :lp=/dev/lpt0:\
        :if=/usr/local/libexec/if-simple:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:sc:\
        :lp=/dev/ttyd5:ms#-parenb cs8 clocal crtscts:rw:\
        :if=/usr/local/libexec/psif:\
        :df=/usr/local/libexec/psdf:

Now, we also need to add the sc capability on the host orchid's /etc/printcap (and while we are at it, let us disable multiple copies for the printer teak):

#
#  /etc/printcap for host orchid - no multiple copies for local
#  printer teak or remote printer bamboo
teak|hp|laserjet|Hewlett Packard LaserJet 3Si:\
        :lp=/dev/lpt0:sd=/var/spool/lpd/teak:mx#0:sc:\
        :if=/usr/local/libexec/ifhp:\
        :vf=/usr/local/libexec/vfhp:\
        :of=/usr/local/libexec/ofhp:

rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :lp=:rm=rose:rp=rattan:sd=/var/spool/lpd/rattan:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :lp=:rm=rose:rp=bamboo:sd=/var/spool/lpd/bamboo:sc:

By using the sc capability, we prevent the use of lpr -#, but that still does not prevent users from running lpr(1) multiple times, or from submitting the same file multiple times in one job like this:

% lpr forsale.sign forsale.sign forsale.sign forsale.sign forsale.sign

There are many ways to prevent this abuse (including ignoring it) which you are free to explore.

9.4.4.2. Restricting Access to Printers

You can control who can print to what printers by using the UNIX® group mechanism and the rg capability in /etc/printcap. Just place the users you want to have access to a printer in a certain group, and then name that group in the rg capability.

Users outside the group (including root) will be greeted with lpr: Not a member of the restricted group if they try to print to the controlled printer.

As with the sc (suppress multiple copies) capability, you need to specify rg on remote hosts that also have access to your printers, if you feel it is appropriate (see section Printers Installed on Remote Hosts).

For example, we will let anyone access the printer rattan, but only those in group artists can use bamboo. Here is the familiar /etc/printcap for host rose:

#
#  /etc/printcap for host rose - restricted group for bamboo
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:sd=/var/spool/lpd/rattan:\
        :lp=/dev/lpt0:\
        :if=/usr/local/libexec/if-simple:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:sc:rg=artists:\
        :lp=/dev/ttyd5:ms#-parenb cs8 clocal crtscts:rw:\
        :if=/usr/local/libexec/psif:\
        :df=/usr/local/libexec/psdf:

Let us leave the other example /etc/printcap file (for the host orchid) alone. Of course, anyone on orchid can print to bamboo. It might be the case that we only allow certain logins on orchid anyway, and want them to have access to the printer. Or not.

注意:

There can be only one restricted group per printer.

9.4.4.3. Controlling Sizes of Jobs Submitted

If you have many users accessing the printers, you probably need to put an upper limit on the sizes of the files users can submit to print. After all, there is only so much free space on the filesystem that houses the spooling directories, and you also need to make sure there is room for the jobs of other users.

LPD enables you to limit the maximum byte size a file in a job can be with the mx capability. The units are in BUFSIZ blocks, which are 1024 bytes. If you put a zero for this capability, there will be no limit on file size; however, if no mx capability is specified, then a default limit of 1000 blocks will be used.

注意:

The limit applies to files in a job, and not the total job size.

LPD will not refuse a file that is larger than the limit you place on a printer. Instead, it will queue as much of the file up to the limit, which will then get printed. The rest will be discarded. Whether this is correct behavior is up for debate.

Let us add limits to our example printers rattan and bamboo. Since those artists' PostScript® files tend to be large, we will limit them to five megabytes. We will put no limit on the plain text line printer:

#
#  /etc/printcap for host rose
#

#
#  No limit on job size:
#
rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:mx#0:sd=/var/spool/lpd/rattan:\
        :lp=/dev/lpt0:\
        :if=/usr/local/libexec/if-simple:

#
#  Limit of five megabytes:
#
bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:sc:rg=artists:mx#5000:\
        :lp=/dev/ttyd5:ms#-parenb cs8 clocal crtscts:rw:\
        :if=/usr/local/libexec/psif:\
        :df=/usr/local/libexec/psdf:

Again, the limits apply to the local users only. If you have set up access to your printers remotely, remote users will not get those limits. You will need to specify the mx capability in the remote /etc/printcap files as well. See section Printers Installed on Remote Hosts for more information on remote printing.

There is another specialized way to limit job sizes from remote printers; see section Restricting Jobs from Remote Printers.

9.4.4.4. Restricting Jobs from Remote Printers

The LPD spooling system provides several ways to restrict print jobs submitted from remote hosts:

Host restrictions

You can control from which remote hosts a local LPD accepts requests with the files /etc/hosts.equiv and /etc/hosts.lpd. LPD checks to see if an incoming request is from a host listed in either one of these files. If not, LPD refuses the request.

The format of these files is simple: one host name per line. Note that the file /etc/hosts.equiv is also used by the ruserok(3) protocol, and affects programs like rsh(1) and rcp(1), so be careful.

For example, here is the /etc/hosts.lpd file on the host rose:

orchid
violet
madrigal.fishbaum.de

This means rose will accept requests from the hosts orchid, violet, and madrigal.fishbaum.de. If any other host tries to access rose's LPD, the job will be refused.

Size restrictions

You can control how much free space there needs to remain on the filesystem where a spooling directory resides. Make a file called minfree in the spooling directory for the local printer. Insert in that file a number representing how many disk blocks (512 bytes) of free space there has to be for a remote job to be accepted.

This lets you insure that remote users will not fill your filesystem. You can also use it to give a certain priority to local users: they will be able to queue jobs long after the free disk space has fallen below the amount specified in the minfree file.

For example, let us add a minfree file for the printer bamboo. We examine /etc/printcap to find the spooling directory for this printer; here is bamboo's entry:

bamboo|ps|PS|S|panasonic|Panasonic KX-P4455 PostScript v51.4:\
        :sh:sd=/var/spool/lpd/bamboo:sc:rg=artists:mx#5000:\
        :lp=/dev/ttyd5:ms#-parenb cs8 clocal crtscts:rw:mx#5000:\
        :if=/usr/local/libexec/psif:\
        :df=/usr/local/libexec/psdf:

The spooling directory is given in the sd capability. We will make three megabytes (which is 6144 disk blocks) the amount of free disk space that must exist on the filesystem for LPD to accept remote jobs:

# echo 6144 > /var/spool/lpd/bamboo/minfree
              
User restrictions

You can control which remote users can print to local printers by specifying the rs capability in /etc/printcap. When rs appears in the entry for a locally-attached printer, LPD will accept jobs from remote hosts if the user submitting the job also has an account of the same login name on the local host. Otherwise, LPD refuses the job.

This capability is particularly useful in an environment where there are (for example) different departments sharing a network, and some users transcend departmental boundaries. By giving them accounts on your systems, they can use your printers from their own departmental systems. If you would rather allow them to use only your printers and not your computer resources, you can give them token accounts, with no home directory and a useless shell like /usr/bin/false.

9.4.5. Accounting for Printer Usage

So, you need to charge for printouts. And why not? Paper and ink cost money. And then there are maintenance costs——printers are loaded with moving parts and tend to break down. You have examined your printers, usage patterns, and maintenance fees and have come up with a per-page (or per-foot, per-meter, or per-whatever) cost. Now, how do you actually start accounting for printouts?

Well, the bad news is the LPD spooling system does not provide much help in this department. Accounting is highly dependent on the kind of printer in use, the formats being printed, and your requirements in charging for printer usage.

To implement accounting, you have to modify a printer's text filter (to charge for plain text jobs) and the conversion filters (to charge for other file formats), to count pages or query the printer for pages printed. You cannot get away with using the simple output filter, since it cannot do accounting. See section Filters.

Generally, there are two ways to do accounting:

  • Periodic accounting is the more common way, possibly because it is easier. Whenever someone prints a job, the filter logs the user, host, and number of pages to an accounting file. Every month, semester, year, or whatever time period you prefer, you collect the accounting files for the various printers, tally up the pages printed by users, and charge for usage. Then you truncate all the logging files, starting with a clean slate for the next period.

  • Timely accounting is less common, probably because it is more difficult. This method has the filters charge users for printouts as soon as they use the printers. Like disk quotas, the accounting is immediate. You can prevent users from printing when their account goes in the red, and might provide a way for users to check and adjust their print quotas. But this method requires some database code to track users and their quotas.

The LPD spooling system supports both methods easily: since you have to provide the filters (well, most of the time), you also have to provide the accounting code. But there is a bright side: you have enormous flexibility in your accounting methods. For example, you choose whether to use periodic or timely accounting. You choose what information to log: user names, host names, job types, pages printed, square footage of paper used, how long the job took to print, and so forth. And you do so by modifying the filters to save this information.

9.4.5.1. Quick and Dirty Printer Accounting

FreeBSD comes with two programs that can get you set up with simple periodic accounting right away. They are the text filter lpf, described in section lpf: a Text Filter, and pac(8), a program to gather and total entries from printer accounting files.

As mentioned in the section on filters (Filters), LPD starts the text and the conversion filters with the name of the accounting file to use on the filter command line. The filters can use this argument to know where to write an accounting file entry. The name of this file comes from the af capability in /etc/printcap, and if not specified as an absolute path, is relative to the spooling directory.

LPD starts lpf with page width and length arguments (from the pw and pl capabilities). lpf uses these arguments to determine how much paper will be used. After sending the file to the printer, it then writes an accounting entry in the accounting file. The entries look like this:

2.00 rose:andy
3.00 rose:kelly
3.00 orchid:mary
5.00 orchid:mary
2.00 orchid:zhang

You should use a separate accounting file for each printer, as lpf has no file locking logic built into it, and two lpfs might corrupt each other's entries if they were to write to the same file at the same time. An easy way to insure a separate accounting file for each printer is to use af=acct in /etc/printcap. Then, each accounting file will be in the spooling directory for a printer, in a file named acct.

When you are ready to charge users for printouts, run the pac(8) program. Just change to the spooling directory for the printer you want to collect on and type pac. You will get a dollar-centric summary like the following:

  Login               pages/feet   runs    price
orchid:kelly                5.00    1   $  0.10
orchid:mary                31.00    3   $  0.62
orchid:zhang                9.00    1   $  0.18
rose:andy                   2.00    1   $  0.04
rose:kelly                177.00  104   $  3.54
rose:mary                  87.00   32   $  1.74
rose:root                  26.00   12   $  0.52

total                     337.00  154   $  6.74

These are the arguments pac(8) expects:

-Pprinter

Which printer to summarize. This option works only if there is an absolute path in the af capability in /etc/printcap.

-c

Sort the output by cost instead of alphabetically by user name.

-m

Ignore host name in the accounting files. With this option, user smith on host alpha is the same user smith on host gamma. Without, they are different users.

-pprice

Compute charges with price dollars per page or per foot instead of the price from the pc capability in /etc/printcap, or two cents (the default). You can specify price as a floating point number.

-r

Reverse the sort order.

-s

Make an accounting summary file and truncate the accounting file.

name

Print accounting information for the given user names only.

In the default summary that pac(8) produces, you see the number of pages printed by each user from various hosts. If, at your site, host does not matter (because users can use any host), run pac -m, to produce the following summary:

  Login               pages/feet   runs    price
andy                        2.00    1   $  0.04
kelly                     182.00  105   $  3.64
mary                      118.00   35   $  2.36
root                       26.00   12   $  0.52
zhang                       9.00    1   $  0.18

total                     337.00  154   $  6.74

To compute the dollar amount due, pac(8) uses the pc capability in the /etc/printcap file (default of 200, or 2 cents per page). Specify, in hundredths of cents, the price per page or per foot you want to charge for printouts in this capability. You can override this value when you run pac(8) with the -p option. The units for the -p option are in dollars, though, not hundredths of cents. For example,

# pac -p1.50

makes each page cost one dollar and fifty cents. You can really rake in the profits by using this option.

Finally, running pac -s will save the summary information in a summary accounting file, which is named the same as the printer's accounting file, but with _sum appended to the name. It then truncates the accounting file. When you run pac(8) again, it rereads the summary file to get starting totals, then adds information from the regular accounting file.

9.4.5.2. How Can You Count Pages Printed?

In order to perform even remotely accurate accounting, you need to be able to determine how much paper a job uses. This is the essential problem of printer accounting.

For plain text jobs, the problem is not that hard to solve: you count how many lines are in a job and compare it to how many lines per page your printer supports. Do not forget to take into account backspaces in the file which overprint lines, or long logical lines that wrap onto one or more additional physical lines.

The text filter lpf (introduced in lpf: a Text Filter) takes into account these things when it does accounting. If you are writing a text filter which needs to do accounting, you might want to examine lpf's source code.

How do you handle other file formats, though?

Well, for DVI-to-LaserJet or DVI-to-PostScript® conversion, you can have your filter parse the diagnostic output of dvilj or dvips and look to see how many pages were converted. You might be able to do similar things with other file formats and conversion programs.

But these methods suffer from the fact that the printer may not actually print all those pages. For example, it could jam, run out of toner, or explode——and the user would still get charged.

So, what can you do?

There is only one sure way to do accurate accounting. Get a printer that can tell you how much paper it uses, and attach it via a serial line or a network connection. Nearly all PostScript® printers support this notion. Other makes and models do as well (networked Imagen laser printers, for example). Modify the filters for these printers to get the page usage after they print each job and have them log accounting information based on that value only. There is no line counting nor error-prone file examination required.

Of course, you can always be generous and make all printouts free.

9.5. Using Printers

This section tells you how to use printers you have set up with FreeBSD. Here is an overview of the user-level commands:

lpr(1)

Print jobs

lpq(1)

Check printer queues

lprm(1)

Remove jobs from a printer's queue

There is also an administrative command, lpc(8), described in the section Administering Printers, used to control printers and their queues.

All three of the commands lpr(1), lprm(1), and lpq(1) accept an option -P printer-name to specify on which printer/queue to operate, as listed in the /etc/printcap file. This enables you to submit, remove, and check on jobs for various printers. If you do not use the -P option, then these commands use the printer specified in the PRINTER environment variable. Finally, if you do not have a PRINTER environment variable, these commands default to the printer named lp.

Hereafter, the terminology default printer means the printer named in the PRINTER environment variable, or the printer named lp when there is no PRINTER environment variable.

9.5.1. Printing Jobs

To print files, type:

% lpr filename ...

This prints each of the listed files to the default printer. If you list no files, lpr(1) reads data to print from standard input. For example, this command prints some important system files:

% lpr /etc/host.conf /etc/hosts.equiv

To select a specific printer, type:

% lpr -P printer-name filename ...

This example prints a long listing of the current directory to the printer named rattan:

% ls -l | lpr -P rattan

Because no files were listed for the lpr(1) command, lpr read the data to print from standard input, which was the output of the ls -l command.

The lpr(1) command can also accept a wide variety of options to control formatting, apply file conversions, generate multiple copies, and so forth. For more information, see the section Printing Options.

9.5.2. Checking Jobs

When you print with lpr(1), the data you wish to print is put together in a package called a print job, which is sent to the LPD spooling system. Each printer has a queue of jobs, and your job waits in that queue along with other jobs from yourself and from other users. The printer prints those jobs in a first-come, first-served order.

To display the queue for the default printer, type lpq(1). For a specific printer, use the -P option. For example, the command

% lpq -P bamboo

shows the queue for the printer named bamboo. Here is an example of the output of the lpq command:

bamboo is ready and printing
Rank   Owner    Job  Files                              Total Size
active kelly    9    /etc/host.conf, /etc/hosts.equiv   88 bytes
2nd    kelly    10   (standard input)                   1635 bytes
3rd    mary     11   ...                                78519 bytes

This shows three jobs in the queue for bamboo. The first job, submitted by user kelly, got assigned job number 9. Every job for a printer gets a unique job number. Most of the time you can ignore the job number, but you will need it if you want to cancel the job; see section Removing Jobs for details.

Job number nine consists of two files; multiple files given on the lpr(1) command line are treated as part of a single job. It is the currently active job (note the word active under the Rank column), which means the printer should be currently printing that job. The second job consists of data passed as the standard input to the lpr(1) command. The third job came from user mary; it is a much larger job. The pathname of the file she is trying to print is too long to fit, so the lpq(1) command just shows three dots.

The very first line of the output from lpq(1) is also useful: it tells what the printer is currently doing (or at least what LPD thinks the printer is doing).

The lpq(1) command also support a -l option to generate a detailed long listing. Here is an example of lpq -l:

waiting for bamboo to become ready (offline ?)
kelly: 1st				 [job 009rose]
       /etc/host.conf                    73 bytes
       /etc/hosts.equiv                  15 bytes

kelly: 2nd				 [job 010rose]
       (standard input)                  1635 bytes

mary: 3rd                                [job 011rose]
      /home/orchid/mary/research/venus/alpha-regio/mapping 78519 bytes

9.5.3. Removing Jobs

If you change your mind about printing a job, you can remove the job from the queue with the lprm(1) command. Often, you can even use lprm(1) to remove an active job, but some or all of the job might still get printed.

To remove a job from the default printer, first use lpq(1) to find the job number. Then type:

% lprm job-number

To remove the job from a specific printer, add the -P option. The following command removes job number 10 from the queue for the printer bamboo:

% lprm -P bamboo 10

The lprm(1) command has a few shortcuts:

lprm -

Removes all jobs (for the default printer) belonging to you.

lprm user

Removes all jobs (for the default printer) belonging to user. The superuser can remove other users' jobs; you can remove only your own jobs.

lprm

With no job number, user name, or - appearing on the command line, lprm(1) removes the currently active job on the default printer, if it belongs to you. The superuser can remove any active job.

Just use the -P option with the above shortcuts to operate on a specific printer instead of the default. For example, the following command removes all jobs for the current user in the queue for the printer named rattan:

% lprm -P rattan -

注意:

If you are working in a networked environment, lprm(1) will let you remove jobs only from the host from which the jobs were submitted, even if the same printer is available from other hosts. The following command sequence demonstrates this:

% lpr -P rattan myfile
% rlogin orchid
% lpq -P rattan
Rank   Owner	  Job  Files                          Total Size
active seeyan	  12	...                           49123 bytes
2nd    kelly      13   myfile                         12 bytes
% lprm -P rattan 13
rose: Permission denied
% logout
% lprm -P rattan 13
dfA013rose dequeued
cfA013rose dequeued
	

9.5.4. Beyond Plain Text: Printing Options

The lpr(1) command supports a number of options that control formatting text, converting graphic and other file formats, producing multiple copies, handling of the job, and more. This section describes the options.

9.5.4.1. Formatting and Conversion Options

The following lpr(1) options control formatting of the files in the job. Use these options if the job does not contain plain text or if you want plain text formatted through the pr(1) utility.

For example, the following command prints a DVI file (from the TeX typesetting system) named fish-report.dvi to the printer named bamboo:

% lpr -P bamboo -d fish-report.dvi

These options apply to every file in the job, so you cannot mix (say) DVI and ditroff files together in a job. Instead, submit the files as separate jobs, using a different conversion option for each job.

注意:

All of these options except -p and -T require conversion filters installed for the destination printer. For example, the -d option requires the DVI conversion filter. Section Conversion Filters gives details.

-c

Print cifplot files.

-d

Print DVI files.

-f

Print FORTRAN text files.

-g

Print plot data.

-i number

Indent the output by number columns; if you omit number, indent by 8 columns. This option works only with certain conversion filters.

注意:

Do not put any space between the -i and the number.

-l

Print literal text data, including control characters.

-n

Print ditroff (device independent troff) data.

-p

Format plain text with pr(1) before printing. See pr(1) for more information.

-T title

Use title on the pr(1) header instead of the file name. This option has effect only when used with the -p option.

-t

Print troff data.

-v

Print raster data.

Here is an example: this command prints a nicely formatted version of the ls(1) manual page on the default printer:

% zcat /usr/share/man/man1/ls.1.gz | troff -t -man | lpr -t

The zcat(1) command uncompresses the source of the ls(1) manual page and passes it to the troff(1) command, which formats that source and makes GNU troff output and passes it to lpr(1), which submits the job to the LPD spooler. Because we used the -t option to lpr(1), the spooler will convert the GNU troff output into a format the default printer can understand when it prints the job.

9.5.4.2. Job Handling Options

The following options to lpr(1) tell LPD to handle the job specially:

-# copies

Produce a number of copies of each file in the job instead of just one copy. An administrator may disable this option to reduce printer wear-and-tear and encourage photocopier usage. See section Restricting Multiple Copies.

This example prints three copies of parser.c followed by three copies of parser.h to the default printer:

% lpr -#3 parser.c parser.h
-m

Send mail after completing the print job. With this option, the LPD system will send mail to your account when it finishes handling your job. In its message, it will tell you if the job completed successfully or if there was an error, and (often) what the error was.

-s

Do not copy the files to the spooling directory, but make symbolic links to them instead.

If you are printing a large job, you probably want to use this option. It saves space in the spooling directory (your job might overflow the free space on the filesystem where the spooling directory resides). It saves time as well since LPD will not have to copy each and every byte of your job to the spooling directory.

There is a drawback, though: since LPD will refer to the original files directly, you cannot modify or remove them until they have been printed.

注意:

If you are printing to a remote printer, LPD will eventually have to copy files from the local host to the remote host, so the -s option will save space only on the local spooling directory, not the remote. It is still useful, though.

-r

Remove the files in the job after copying them to the spooling directory, or after printing them with the -s option. Be careful with this option!

9.5.4.3. Header Page Options

These options to lpr(1) adjust the text that normally appears on a job's header page. If header pages are suppressed for the destination printer, these options have no effect. See section Header Pages for information about setting up header pages.

-C text

Replace the hostname on the header page with text. The hostname is normally the name of the host from which the job was submitted.

-J text

Replace the job name on the header page with text. The job name is normally the name of the first file of the job, or stdin if you are printing standard input.

-h

Do not print any header page.

注意:

At some sites, this option may have no effect due to the way header pages are generated. See Header Pages for details.

9.5.5. Administering Printers

As an administrator for your printers, you have had to install, set up, and test them. Using the lpc(8) command, you can interact with your printers in yet more ways. With lpc(8), you can

  • Start and stop the printers

  • Enable and disable their queues

  • Rearrange the order of the jobs in each queue.

First, a note about terminology: if a printer is stopped, it will not print anything in its queue. Users can still submit jobs, which will wait in the queue until the printer is started or the queue is cleared.

If a queue is disabled, no user (except root) can submit jobs for the printer. An enabled queue allows jobs to be submitted. A printer can be started for a disabled queue, in which case it will continue to print jobs in the queue until the queue is empty.

In general, you have to have root privileges to use the lpc(8) command. Ordinary users can use the lpc(8) command to get printer status and to restart a hung printer only.

Here is a summary of the lpc(8) commands. Most of the commands take a printer-name argument to tell on which printer to operate. You can use all for the printer-name to mean all printers listed in /etc/printcap.

abort printer-name

Cancel the current job and stop the printer. Users can still submit jobs if the queue is enabled.

clean printer-name

Remove old files from the printer's spooling directory. Occasionally, the files that make up a job are not properly removed by LPD, particularly if there have been errors during printing or a lot of administrative activity. This command finds files that do not belong in the spooling directory and removes them.

disable printer-name

Disable queuing of new jobs. If the printer is running, it will continue to print any jobs remaining in the queue. The superuser (root) can always submit jobs, even to a disabled queue.

This command is useful while you are testing a new printer or filter installation: disable the queue and submit jobs as root. Other users will not be able to submit jobs until you complete your testing and re-enable the queue with the enable command.

down printer-name message

Take a printer down. Equivalent to disable followed by stop. The message appears as the printer's status whenever a user checks the printer's queue with lpq(1) or status with lpc status.

enable printer-name

Enable the queue for a printer. Users can submit jobs but the printer will not print anything until it is started.

help command-name

Print help on the command command-name. With no command-name, print a summary of the commands available.

restart printer-name

Start the printer. Ordinary users can use this command if some extraordinary circumstance hangs LPD, but they cannot start a printer stopped with either the stop or down commands. The restart command is equivalent to abort followed by start.

start printer-name

Start the printer. The printer will print jobs in its queue.

stop printer-name

Stop the printer. The printer will finish the current job and will not print anything else in its queue. Even though the printer is stopped, users can still submit jobs to an enabled queue.

topq printer-name job-or-username

Rearrange the queue for printer-name by placing the jobs with the listed job numbers or the jobs belonging to username at the top of the queue. For this command, you cannot use all as the printer-name.

up printer-name

Bring a printer up; the opposite of the down command. Equivalent to start followed by enable.

lpc(8) accepts the above commands on the command line. If you do not enter any commands, lpc(8) enters an interactive mode, where you can enter commands until you type exit, quit, or end-of-file.

9.6. Alternatives to the Standard Spooler

If you have been reading straight through this manual, by now you have learned just about everything there is to know about the LPD spooling system that comes with FreeBSD. You can probably appreciate many of its shortcomings, which naturally leads to the question: What other spooling systems are out there (and work with FreeBSD)?

LPRng

LPRng, which purportedly means LPR: the Next Generation is a complete rewrite of PLP. Patrick Powell and Justin Mason (the principal maintainer of PLP) collaborated to make LPRng. The main site for LPRng is http://www.lprng.org/.

CUPS

CUPS, the Common UNIX Printing System, provides a portable printing layer for UNIX®-based operating systems. It has been developed by Easy Software Products to promote a standard printing solution for all UNIX® vendors and users.

CUPS uses the Internet Printing Protocol (IPP) as the basis for managing print jobs and queues. The Line Printer Daemon (LPD), Server Message Block (SMB), and AppSocket (a.k.a. JetDirect) protocols are also supported with reduced functionality. CUPS adds network printer browsing and PostScript Printer Description (PPD) based printing options to support real-world printing under UNIX®.

The main site for CUPS is http://www.cups.org/.

9.7. Troubleshooting

After performing the simple test with lptest(1), you might have gotten one of the following results instead of the correct printout:

It worked, after awhile; or, it did not eject a full sheet.

The printer printed the above, but it sat for awhile and did nothing. In fact, you might have needed to press a PRINT REMAINING or FORM FEED button on the printer to get any results to appear.

If this is the case, the printer was probably waiting to see if there was any more data for your job before it printed anything. To fix this problem, you can have the text filter send a FORM FEED character (or whatever is necessary) to the printer. This is usually sufficient to have the printer immediately print any text remaining in its internal buffer. It is also useful to make sure each print job ends on a full sheet, so the next job does not start somewhere on the middle of the last page of the previous job.

The following replacement for the shell script /usr/local/libexec/if-simple prints a form feed after it sends the job to the printer:

#!/bin/sh
#
# if-simple - Simple text input filter for lpd
# Installed in /usr/local/libexec/if-simple
#
# Simply copies stdin to stdout.  Ignores all filter arguments.
# Writes a form feed character (\f) after printing job.

/bin/cat && printf "\f" && exit 0
exit 2
It produced the staircase effect.

You got the following on paper:

!"#$%&'()*+,-./01234
                "#$%&'()*+,-./012345
                                 #$%&'()*+,-./0123456

You have become another victim of the staircase effect, caused by conflicting interpretations of what characters should indicate a new line. UNIX® style operating systems use a single character: ASCII code 10, the line feed (LF). MS-DOS®, OS/2®, and others uses a pair of characters, ASCII code 10 and ASCII code 13 (the carriage return or CR). Many printers use the MS-DOS® convention for representing new-lines.

When you print with FreeBSD, your text used just the line feed character. The printer, upon seeing a line feed character, advanced the paper one line, but maintained the same horizontal position on the page for the next character to print. That is what the carriage return is for: to move the location of the next character to print to the left edge of the paper.

Here is what FreeBSD wants your printer to do:

Printer received CRPrinter prints CR
Printer received LFPrinter prints CR + LF

Here are some ways to achieve this:

  • Use the printer's configuration switches or control panel to alter its interpretation of these characters. Check your printer's manual to find out how to do this.

    注意:

    If you boot your system into other operating systems besides FreeBSD, you may have to reconfigure the printer to use a an interpretation for CR and LF characters that those other operating systems use. You might prefer one of the other solutions, below.

  • Have FreeBSD's serial line driver automatically convert LF to CR+LF. Of course, this works with printers on serial ports only. To enable this feature, use the ms# capability and set the onlcr mode in the /etc/printcap file for the printer.

  • Send an escape code to the printer to have it temporarily treat LF characters differently. Consult your printer's manual for escape codes that your printer might support. When you find the proper escape code, modify the text filter to send the code first, then send the print job.

    Here is an example text filter for printers that understand the Hewlett-Packard PCL escape codes. This filter makes the printer treat LF characters as a LF and CR; then it sends the job; then it sends a form feed to eject the last page of the job. It should work with nearly all Hewlett Packard printers.

    #!/bin/sh
    #
    # hpif - Simple text input filter for lpd for HP-PCL based printers
    # Installed in /usr/local/libexec/hpif
    #
    # Simply copies stdin to stdout.  Ignores all filter arguments.
    # Tells printer to treat LF as CR+LF.  Ejects the page when done.
    
    printf "\033&k2G" && cat && printf "\033&l0H" && exit 0
    exit 2

    Here is an example /etc/printcap from a host called orchid. It has a single printer attached to its first parallel port, a Hewlett Packard LaserJet 3Si named teak. It is using the above script as its text filter:

    #
    #  /etc/printcap for host orchid
    #
    teak|hp|laserjet|Hewlett Packard LaserJet 3Si:\
            :lp=/dev/lpt0:sh:sd=/var/spool/lpd/teak:mx#0:\
            :if=/usr/local/libexec/hpif:
It overprinted each line.

The printer never advanced a line. All of the lines of text were printed on top of each other on one line.

This problem is the opposite of the staircase effect, described above, and is much rarer. Somewhere, the LF characters that FreeBSD uses to end a line are being treated as CR characters to return the print location to the left edge of the paper, but not also down a line.

Use the printer's configuration switches or control panel to enforce the following interpretation of LF and CR characters:

Printer receivesPrinter prints
CRCR
LFCR + LF
The printer lost characters.

While printing, the printer did not print a few characters in each line. The problem might have gotten worse as the printer ran, losing more and more characters.

The problem is that the printer cannot keep up with the speed at which the computer sends data over a serial line (this problem should not occur with printers on parallel ports). There are two ways to overcome the problem:

  • If the printer supports XON/XOFF flow control, have FreeBSD use it by specifying the ixon mode in the ms# capability.

  • If the printer supports carrier flow control, specify the crtscts mode in the ms# capability. Make sure the cable connecting the printer to the computer is correctly wired for carrier flow control.

It printed garbage.

The printer printed what appeared to be random garbage, but not the desired text.

This is usually another symptom of incorrect communications parameters with a serial printer. Double-check the bps rate in the br capability, and the parity setting in the ms# capability; make sure the printer is using the same settings as specified in the /etc/printcap file.

Nothing happened.

If nothing happened, the problem is probably within FreeBSD and not the hardware. Add the log file (lf) capability to the entry for the printer you are debugging in the /etc/printcap file. For example, here is the entry for rattan, with the lf capability:

rattan|line|diablo|lp|Diablo 630 Line Printer:\
        :sh:sd=/var/spool/lpd/rattan:\
        :lp=/dev/lpt0:\
        :if=/usr/local/libexec/if-simple:\
        :lf=/var/log/rattan.log

Then, try printing again. Check the log file (in our example, /var/log/rattan.log) to see any error messages that might appear. Based on the messages you see, try to correct the problem.

If you do not specify a lf capability, LPD uses /dev/console as a default.

章 10. Linux® 二進位檔的相容性

Restructured and parts updated by Jim Mock.
Originally contributed by Brian N. HandyRich Murphey.

10.1. 概述

FreeBSD 提供和32位元 Linux® 二進位檔的相容性,允許使用者在 FreeBSD不需要修改就可以安裝和執行大部份32位元 Linux® 二進位檔。 曾經有人指出,在某些情況下,32位元 Linux®二進位檔在 FreeBSD 的表現比在 Linux®好。

然而,某些However, some Linux®作業系統的特色在 FreeBSD 並未支援。 例如,如果 Linux® 二進位檔過度使用i386™特定的呼叫,像是啟動虛擬8086模式,將無法在 FreeBSD 執行。此外,64位元 Linux® 二進位檔目前也尚未支援。

讀完本章後,您將了解:

  • 如何在FreeBSD系統啟用 Linux® 相容模式 FreeBSD。

  • 如何安裝額外的 Linux® 共享程式庫。

  • 如何在FreeBSD系統安裝 Linux® 應用程式。

  • The implementation details of Linux® compatibility in FreeBSD.

在閱讀這章之前,您應當了解:

10.2. 設置 Linux® 二進位檔相容性

Linux® 程式庫並未預設安裝,而且 Linux® 二進位檔相容性並未啟用。 Linux® 程式庫可以手動安裝或是從 FreeBSD Ports 安裝。

編譯 port 前,要載入 Linux® 核心模組,否則編譯會失敗:

# kldload linux

確認模組已載入:

% kldstat
      Id Refs Address    Size     Name
      1    2 0xc0100000 16bdb8   kernel
      7    1 0xc24db000 d000     linux.ko

在 FreeBSD 安裝基本的 Linux® 程式庫和二進位檔最簡單的方式是安裝 emulators/linux_base-c6 套件或是 port 。安裝 port:

# printf "compat.linux.osrelease=2.6.18\n" >> /etc/sysctl.conf
# sysctl compat.linux.osrelease=2.6.18
# pkg install emulators/linux_base-c6

要讓 Linux® 相容性在開機時就啟用,可以加入這行到 /etc/rc.conf:

linux_enable="YES"

想要靜態連結 Linux® 二進位檔相容性到自訂核心的使用者應該增加 options COMPAT_LINUX 到他們自訂核心設定檔。 編譯和安裝新核心的方法,如 章 8, 設定 FreeBSD Kernel所述。

10.2.1. 手動安裝額外的程式庫

如果一個 Linux® 應用程式在設定 Linux®二進位檔相容性後表示缺少共享程式庫, 看看這個Linux® 二進位檔需要哪個共享程式庫,手動安裝他。

Linux® 系統中, ldd 可以用來決定應用程式需要哪個。 例如,檢查 linuxdoom 需要哪個共享程式庫,從安裝 DoomLinux® 系統中執行這個指令:

% ldd linuxdoom
libXt.so.3 (DLL Jump 3.1) => /usr/X11/lib/libXt.so.3.1.0
libX11.so.3 (DLL Jump 3.1) => /usr/X11/lib/libX11.so.3.1.0
libc.so.4 (DLL Jump 4.5pl26) => /lib/libc.so.4.6.29

然後,複製所有 Linux® 系統輸出最後一欄的檔案到 FreeBSD系統的 /compat/linux 。 複製完後,建立符號連結到剛剛輸出第一欄的名字。這個例子會在 FreeBSD 系統產生以下檔案:

/compat/linux/usr/X11/lib/libXt.so.3.1.0
/compat/linux/usr/X11/lib/libXt.so.3 -> libXt.so.3.1.0
/compat/linux/usr/X11/lib/libX11.so.3.1.0
/compat/linux/usr/X11/lib/libX11.so.3 -> libX11.so.3.1.0
/compat/linux/lib/libc.so.4.6.29
/compat/linux/lib/libc.so.4 -> libc.so.4.6.29

If a Linux® shared library already exists with a matching major revision number to the first column of the ldd output, it does not need to be copied to the file named in the last column, as the existing library should work. It is advisable to copy the shared library if it is a newer version, though. The old one can be removed, as long as the symbolic link points to the new one.

For example, these libraries already exist on the FreeBSD system:

/compat/linux/lib/libc.so.4.6.27
/compat/linux/lib/libc.so.4 -> libc.so.4.6.27

and ldd indicates that a binary requires a later version:

libc.so.4 (DLL Jump 4.5pl26) -> libc.so.4.6.29

Since the existing library is only one or two versions out of date in the last digit, the program should still work with the slightly older version. However, it is safe to replace the existing libc.so with the newer version:

/compat/linux/lib/libc.so.4.6.29
/compat/linux/lib/libc.so.4 -> libc.so.4.6.29

Generally, one will need to look for the shared libraries that Linux® binaries depend on only the first few times that a Linux® program is installed on FreeBSD. After a while, there will be a sufficient set of Linux® shared libraries on the system to be able to run newly installed Linux® binaries without any extra work.

10.2.2. 安裝 Linux® ELF 二進位檔

ELF 二進位等有時候需要額外的步驟。當執行未標記的 ELF 二進位檔,會產生錯誤訊息:

% ./my-linux-elf-binary
ELF binary type not known
Abort

為了幫 FreeBSD 核心辨識 FreeBSD ELF 二進位檔和 Linux® 二進位檔,使用 brandelf(1)

% brandelf -t Linux my-linux-elf-binary

因為GNU工具鏈會自動放置適當的標記資訊進 ELF 二進位檔,通常就不需要這個步驟。

10.2.3. 安裝 Linux® RPM 基礎的應用程式

要安裝 Linux® RPM 基礎的應用程式,先安裝 archivers/rpm 套件或 port。 安裝後, root 可以使用這個指令來安裝.rpm檔:

# cd /compat/linux
# rpm2cpio < /path/to/linux.archive.rpm | cpio -id

如果需要, brandelf 已安裝的 ELF二進位檔。注意,這將會無法乾淨地解除安裝。

10.2.4. 設定主機名稱解析器(Hostname Resolver)

如果 DNS 有問題或是出現這個錯誤:

resolv+: "bind" is an invalid keyword resolv+:
"hosts" is an invalid keyword

/compat/linux/etc/host.conf設定如下:

order hosts, bind
multi on

這指定先搜尋 /etc/hostsDNS 次之。 當 /compat/linux/etc/host.conf 不存在, Linux® 應用程式會使用 /etc/host.conf 並會抱怨不相容的 FreeBSD 語法。 如果名稱伺服器未設定使用/etc/resolv.conf的話,移除 bind

10.3. 進階主題

本節描述 Linux® 二進位檔如何運作,以 Terry Lambert 寫給FreeBSD chat 郵遞論壇的電子郵件為基礎(Message ID: <199906020108.SAA07001@usr09.primenet.com>)。

FreeBSD has an abstraction called an execution class loader. This is a wedge into the execve(2) system call.

歷史上, UNIX® 載入器檢查魔術數字(通常是檔案的頭四或八個位元組)來看它是否是系統已知的二進位檔,如果是,就調用二進位檔載入器。

如果不是系統的二進位檔類型, execve(2) 呼叫會回報失敗,shell會嘗試當作 shell 指令來執行。 The assumption was a default of whatever the current shell is.

後來, sh(1) 做了hack來檢查頭兩字元,如果他們是 :\n,就改調用 csh(1) shell 。

FreeBSD 有一系列的載入器取代單一載入器,其中有with a fallback to the #! 載入器來執行 shell 解譯器或是 shell 腳本。

對於 Linux® ABI 支援, FreeBSD 將魔術數字看待為 ELF 二進位檔。 ELF載入器尋找專門的 brand,這是 ELF 影像的註解部份,並未存在於 SVR4/Solaris™ ELF 二進位檔。

For Linux® binaries to function, they must be branded as type Linux using brandelf(1):

# brandelf -t Linux file

When the ELF loader sees the Linux brand, the loader replaces a pointer in the proc structure. All system calls are indexed through this pointer. In addition, the process is flagged for special handling of the trap vector for the signal trampoline code, and several other (minor) fix-ups that are handled by the Linux® kernel module.

The Linux® system call vector contains, among other things, a list of sysent[] entries whose addresses reside in the kernel module.

When a system call is called by the Linux® binary, the trap code dereferences the system call function pointer off the proc structure, and gets the Linux®, not the FreeBSD, system call entry points.

Linux® mode dynamically reroots lookups. This is, in effect, equivalent to the union option to file system mounts. First, an attempt is made to lookup the file in /compat/linux/original-path. If that fails, the lookup is done in /original-path. This makes sure that binaries that require other binaries can run. For example, the Linux® toolchain can all run under Linux® ABI support. It also means that the Linux® binaries can load and execute FreeBSD binaries, if there are no corresponding Linux® binaries present, and that a uname(1) command can be placed in the /compat/linux directory tree to ensure that the Linux® binaries can not tell they are not running on Linux®.

In effect, there is a Linux® kernel in the FreeBSD kernel. The various underlying functions that implement all of the services provided by the kernel are identical to both the FreeBSD system call table entries, and the Linux® system call table entries: file system operations, virtual memory operations, signal delivery, and System V IPC. The only difference is that FreeBSD binaries get the FreeBSD glue functions, and Linux® binaries get the Linux® glue functions. The FreeBSD glue functions are statically linked into the kernel, and the Linux® glue functions can be statically linked, or they can be accessed via a kernel module.

Technically, this is not really emulation, it is an ABI implementation. It is sometimes called Linux® emulation because the implementation was done at a time when there was no other word to describe what was going on. Saying that FreeBSD ran Linux® binaries was not true, since the code was not compiled in.

部 III. 系統管理

FreeBSD 使用手冊剩下的這些章節涵蓋了全方位的 FreeBSD 系統管理。 每個章節的開頭會先描述在該您讀完該章節後您會學到什麼,也會詳述在您在看這些資料時應該要有的一些背景知識。

這些章節是讓您在需要查資料的時候翻閱用的。 您不需要依照特定的順序來讀,也不需要將這些章節全部過讀之後才開始用 FreeBSD。

內容目錄
11. 設定與效能調校(Tuning)
11.1. 概述
11.2. 最主要的設定檔
11.3. 各式應用程式的設定檔
11.4. 各種 Services 的啟動方式
11.5. 設定 cron
11.6. 在 FreeBSD 使用 rc
11.7. 設定網路卡
11.8. 虛擬主機(Virtual Hosts)
11.9. 還有哪些主要設定檔呢?
11.10. Tuning with sysctl
11.11. Tuning Disks
11.12. Tuning Kernel Limits
11.13. Adding Swap Space
11.14. Power and Resource Management
11.15. Using and Debugging FreeBSD ACPI
12. FreeBSD 開機流程篇
12.1. 概述
12.2. Booting 問題
12.3. The Boot Manager and Boot Stages
12.4. Kernel Interaction During Boot
12.5. Device Hints
12.6. Init: Process Control Initialization
12.7. Shutdown Sequence
13. 系統安全
13.1. 概述
13.2. Introduction
13.3. One-time Passwords
13.4. TCP Wrapper
13.5. Kerberos
13.6. OpenSSL
13.7. VPN over IPsec
13.8. OpenSSH
13.9. Access Control Lists
13.10. Monitoring Third Party Security Issues
13.11. FreeBSD Security Advisories
13.12. Process Accounting
13.13. Resource Limits
14. Jails
14.1. 概述
14.2. Jail 相關術語
14.3. 背景故事
14.4. 建立和控制 Jail
14.5. 微調與管理
14.6. Jail 的應用
15. Mandatory Access Control
15.1. Synopsis
15.2. Key Terms in this Chapter
15.3. Explanation of MAC
15.4. Understanding MAC Labels
15.5. Module Configuration
15.6. The MAC bsdextended Module
15.7. The MAC ifoff Module
15.8. The MAC portacl Module
15.9. MAC Policies with Labeling Features
15.10. The MAC partition Module
15.11. The MAC Multi-Level Security Module
15.12. The MAC Biba Module
15.13. The MAC LOMAC Module
15.14. Implementing a Secure Environment with MAC
15.15. Another Example: Using MAC to Constrain a Web Server
15.16. Troubleshooting the MAC Framework
16. Security Event Auditing
16.1. Synopsis
16.2. Key Terms - Words to Know
16.3. Installing Audit Support
16.4. Audit Configuration
16.5. Event Audit Administration
17. 儲存設備篇
17.1. 概述
17.2. 裝置名稱
17.3. 新增磁碟
17.4. Resizing and Growing Disks
17.5. USB 儲存裝置
17.6. Creating and Using CD Media
17.7. Creating and Using DVD Media
17.8. Creating and Using Floppy Disks
17.9. Backup Basics
17.10. Memory Disks
17.11. File System Snapshots
17.12. 磁碟空間配額(Quota)
17.13. Encrypting Disk Partitions
17.14. Encrypting Swap
17.15. Highly Available Storage (HAST)
18. GEOM: Modular Disk Transformation Framework
18.1. 概述
18.2. RAID0 - 分散連結(striping)
18.3. RAID1 - 鏡射(Mirroring)
18.4. RAID3 - Byte-level Striping with Dedicated Parity
18.5. Software RAID Devices
18.6. GEOM Gate Network
18.7. Labeling Disk Devices
18.8. UFS Journaling Through GEOM
19. The Z File System (ZFS)
19.1. What Makes ZFS Different
19.2. Quick Start Guide
19.3. zpool Administration
19.4. zfs Administration
19.5. Delegated Administration
19.6. Advanced Topics
19.7. Additional Resources
19.8. ZFS Features and Terminology
20. Other File Systems
20.1. Synopsis
20.2. Linux® File Systems
21. Virtualization(虛擬機器)
21.1. Synopsis
21.2. 安裝 FreeBSD 為 Guest OS
21.3. 以 FreeBSD 為 Host OS
22. 語系設定 - I18N/L10N 用法與設定
22.1. 概述
22.2. L10N 基礎概念
22.3. 使用語系設定(Localization)
22.4. Compiling I18N Programs
22.5. Localizing FreeBSD to Specific Languages
23. 更新、升級 FreeBSD
23.1. 概述
23.2. FreeBSD Update
23.3. 更新文件組
23.4. 追蹤發展分支
23.5. 同步原始碼
23.6. 重新編譯 World
23.7. 追蹤多追蹤多部機器
24. DTrace
24.1. Synopsis
24.2. Implementation Differences
24.3. Enabling DTrace Support
24.4. Using DTrace

章 11. 設定與效能調校(Tuning)

Written by Chern Lee.
Based on a tutorial written by Mike Smith.
Also based on tuning(7) written by Matt Dillon.

11.1. 概述

在 FreeBSD 使用過程中,相當重要的環節之一就是系統設定部分。 正確的系統設定,可以讓你減輕日後升級的頭痛壓力。 本章著重於介紹 FreeBSD 的相關重要設定上,包括一些可以調整 FreeBSD 效能的參數設定。

讀完這章,您將了解:

  • 如何有效運用檔案系統以及 swap 分割區。

  • rc.conf 的設定與 /usr/local/etc/rc.d 的啟動架構。

  • 如何設定、測試網路卡。

  • 如何設定 virtual hosts。

  • 如何設定 /etc 內的各種設定檔。

  • 如何以 sysctl 來調整 FreeBSD 的系統效能。

  • 如何調整硬碟效能,以及更改 kernel 限制。

在開始閱讀這章之前,您需要︰

11.2. 最主要的設定檔

The principal location for system configuration information is within /etc/rc.conf. This file contains a wide range of configuration information, principally used at system startup to configure the system. Its name directly implies this; it is configuration information for the rc* files.

An administrator should make entries in the rc.conf file to override the default settings from /etc/defaults/rc.conf. The defaults file should not be copied verbatim to /etc - it contains default values, not examples. All system-specific changes should be made in the rc.conf file itself.

A number of strategies may be applied in clustered applications to separate site-wide configuration from system-specific configuration in order to keep administration overhead down. The recommended approach is to place site-wide configuration into another file, such as /etc/rc.conf.site, and then include this file into /etc/rc.conf, which will contain only system-specific information.

As rc.conf is read by sh(1) it is trivial to achieve this. For example:

  • rc.conf:

    	. /etc/rc.conf.site
    	hostname="node15.example.com"
    	network_interfaces="fxp0 lo0"
    	ifconfig_fxp0="inet 10.1.1.1"
  • rc.conf.site:

    	defaultrouter="10.1.1.254"
    	saver="daemon"
    	blanktime="100"

The rc.conf.site file can then be distributed to every system using rsync or a similar program, while the rc.conf file remains unique.

Upgrading the system using sysinstall(8) or make world will not overwrite the rc.conf file, so system configuration information will not be lost.

11.3. 各式應用程式的設定檔

原則上,安裝的軟體都會有其自有的設定檔,也會有自己的格式及語法。 因此,將其與系統分開獨立是件非常重要的事情。如此一來,套件管理工具將可以 很輕易的找出這些設定檔並管理這些設定檔。

原則上,設定檔會被放置在 /usr/local/etc。 若某軟體的設定檔為數眾多,那將會其下建立一個目錄以供放置

通常,當一個 port 或 package 被安裝的同時,一些基本的設定範例 也會一併被安裝至此。這些範例通常會被用 .default 做為副檔名。 若安裝時沒有自行撰寫的軟體設定檔,那麼將會複製一份 .default 設定 做為預設設定檔

舉個例子,我們來看看 /usr/local/etc/apache

-rw-r--r--  1 root  wheel   2184 May 20  1998 access.conf
-rw-r--r--  1 root  wheel   2184 May 20  1998 access.conf.default
-rw-r--r--  1 root  wheel   9555 May 20  1998 httpd.conf
-rw-r--r--  1 root  wheel   9555 May 20  1998 httpd.conf.default
-rw-r--r--  1 root  wheel  12205 May 20  1998 magic
-rw-r--r--  1 root  wheel  12205 May 20  1998 magic.default
-rw-r--r--  1 root  wheel   2700 May 20  1998 mime.types
-rw-r--r--  1 root  wheel   2700 May 20  1998 mime.types.default
-rw-r--r--  1 root  wheel   7980 May 20  1998 srm.conf
-rw-r--r--  1 root  wheel   7933 May 20  1998 srm.conf.default

srm.conf 的檔案被修改過了,爾後 Apache 的更新 將不會對這個已修改過的設定檔做任何變動。

11.4. 各種 Services 的啟動方式

Contributed by Tom Rhodes.

Many users choose to install third party software on FreeBSD from the Ports Collection. In many of these situations it may be necessary to configure the software in a manner which will allow it to be started upon system initialization. Services, such as mail/postfix or www/apache13 are just two of the many software packages which may be started during system initialization. This section explains the procedures available for starting third party software.

In FreeBSD, most included services, such as cron(8), are started through the system start up scripts. These scripts may differ depending on FreeBSD or vendor version; however, the most important aspect to consider is that their start up configuration can be handled through simple startup scripts.

Before the advent of rc.d, applications would drop a simple start up script into the /usr/local/etc/rc.d directory which would be read by the system initialization scripts. These scripts would then be executed during the latter stages of system start up.

While many individuals have spent hours trying to merge the old configuration style into the new system, the fact remains that some third party utilities still require a script simply dropped into the aforementioned directory. The subtle differences in the scripts depend whether or not rc.d is being used. Prior to FreeBSD 5.1 the old configuration style is used and in almost all cases a new style script would do just fine.

While every script must meet some minimal requirements, most of the time these requirements are FreeBSD version agnostic. Each script must have a .sh extension appended to the end and every script must be executable by the system. The latter may be achieved by using the chmod command and setting the unique permissions of 755. There should also be, at minimal, an option to start the application and an option to stop the application.

The simplest start up script would probably look a little bit like this one:

#!/bin/sh
echo -n ' utility'

case "$1" in
start)
        /usr/local/bin/utility
        ;;
stop)
        kill -9 `cat /var/run/utility.pid`
        ;;
*)
        echo "Usage: `basename $0` {start|stop}" >&2
        exit 64
        ;;
esac

exit 0

This script provides for a stop and start option for the application hereto referred simply as utility.

Could be started manually with:

# /usr/local/etc/rc.d/utility.sh start

While not all third party software requires the line in rc.conf, almost every day a new port will be modified to accept this configuration. Check the final output of the installation for more information on a specific application. Some third party software will provide start up scripts which permit the application to be used with rc.d; although, this will be discussed in the next section.

11.4.1. Extended Application Configuration

Now that FreeBSD includes rc.d, configuration of application startup has become easier, and more featureful. Using the key words discussed in the rc.d section, applications may now be set to start after certain other services for example DNS; may permit extra flags to be passed through rc.conf in place of hard coded flags in the start up script, etc. A basic script may look similar to the following:

#!/bin/sh
#
# PROVIDE: utility
# REQUIRE: DAEMON
# KEYWORD: shutdown

. /etc/rc.subr

name=utility
rcvar=utility_pidfile

command="/usr/local/sbin/utility"

load_rc_config $name

#
# DO NOT CHANGE THESE DEFAULT VALUES HERE
# SET THEM IN THE /etc/rc.conf FILE
#
utility_enable=${utility_enable-"NO"}
pidfile=${utility_pidfile-"/var/run/utility.pid"}

run_rc_command "$1"

This script will ensure that the provided utility will be started after the daemon service. It also provides a method for setting and tracking the PID, or process ID file.

This application could then have the following line placed in /etc/rc.conf:

utility_enable="YES"

This new method also allows for easier manipulation of the command line arguments, inclusion of the default functions provided in /etc/rc.subr, compatibility with the rcorder(8) utility and provides for easier configuration via the rc.conf file.

11.4.2. 以 Services 來啟動各式 Services

Other services, such as POP3 server daemons, IMAP, etc. could be started using the inetd(8). This involves installing the service utility from the Ports Collection with a configuration line appended to the /etc/inetd.conf file, or uncommenting one of the current configuration lines. Working with inetd and its configuration is described in depth in the inetd section.

In some cases, it may be more plausible to use the cron(8) daemon to start system services. This approach has a number of advantages because cron runs these processes as the crontab's file owner. This allows regular users to start and maintain some applications.

The cron utility provides a unique feature, @reboot, which may be used in place of the time specification. This will cause the job to be run when cron(8) is started, normally during system initialization.

11.5. 設定 cron

Contributed by Tom Rhodes.

FreeBSD 最好用的工具之一就是 cron(8)cron 會在背景下運作,並不斷檢查 /etc/crontab 檔以及 /var/cron/tabs 目錄,來搜尋是否有新 crontab 檔案。 這些 crontab 檔會存放一些排程工作的設定,來給 cron 執行。

cron 程式,可同時採用兩種不同類型的設定檔:系統本身的 crontab 及使用者本身的 crontab。而兩種格式唯一差別在於第六欄的不同;In the system crontab, the sixth field is the name of a user for the command to run as. This gives the system crontab the ability to run commands as any user. In a user crontab, the sixth field is the command to run, and all commands run as the user who created the crontab; this is an important security feature.

注意:

User crontabs allow individual users to schedule tasks without the need for root privileges. Commands in a user's crontab run with the permissions of the user who owns the crontab.

The root user can have a user crontab just like any other user. This one is different from /etc/crontab (the system crontab). Because of the system crontab, there is usually no need to create a user crontab for root.

Let us take a look at the /etc/crontab file (the system crontab):

# /etc/crontab - root's crontab for FreeBSD
#
# $FreeBSD: src/etc/crontab,v 1.32 2002/11/22 16:13:39 tom Exp $
# 1
#
SHELL=/bin/sh
PATH=/etc:/bin:/sbin:/usr/bin:/usr/sbin 2
HOME=/var/log
#
#
#minute	hour	mday	month	wday	who	command 3
#
#
*/5	*	*	*	*	root	/usr/libexec/atrun 4

1

Like most FreeBSD configuration files, the # character represents a comment. A comment can be placed in the file as a reminder of what and why a desired action is performed. Comments cannot be on the same line as a command or else they will be interpreted as part of the command; they must be on a new line. Blank lines are ignored.

2

First, the environment must be defined. The equals (=) character is used to define any environment settings, as with this example where it is used for the SHELL, PATH, and HOME options. If the shell line is omitted, cron will use the default, which is sh. If the PATH variable is omitted, no default will be used and file locations will need to be absolute. If HOME is omitted, cron will use the invoking users home directory.

3

This line defines a total of seven fields. Listed here are the values minute, hour, mday, month, wday, who, and command. These are almost all self explanatory. minute is the time in minutes the command will be run. hour is similar to the minute option, just in hours. mday stands for day of the month. month is similar to hour and minute, as it designates the month. The wday option stands for day of the week. All these fields must be numeric values, and follow the twenty-four hour clock. The who field is special, and only exists in the /etc/crontab file. This field specifies which user the command should be run as. When a user installs his or her crontab file, they will not have this option. Finally, the command option is listed. This is the last field, so naturally it should designate the command to be executed.

4

This last line will define the values discussed above. Notice here we have a */5 listing, followed by several more * characters. These * characters mean first-last, and can be interpreted as every time. So, judging by this line, it is apparent that the atrun command is to be invoked by root every five minutes regardless of what day or month it is. For more information on the atrun command, see the atrun(8) manual page.

Commands can have any number of flags passed to them; however, commands which extend to multiple lines need to be broken with the backslash \ continuation character.

This is the basic set up for every crontab file, although there is one thing different about this one. Field number six, where we specified the username, only exists in the system /etc/crontab file. This field should be omitted for individual user crontab files.

11.5.1. 工作排程(Crontab)的排定與管理

重要:

You must not use the procedure described here to edit/install the system crontab. Simply use your favorite editor: the cron utility will notice that the file has changed and immediately begin using the updated version. See this FAQ entry for more information.

To install a freshly written user crontab, first use your favorite editor to create a file in the proper format, and then use the crontab utility. The most common usage is:

% crontab crontab-file

In this example, crontab-file is the filename of a crontab that was previously created.

There is also an option to list installed crontab files: just pass the -l option to crontab and look over the output.

For users who wish to begin their own crontab file from scratch, without the use of a template, the crontab -e option is available. This will invoke the selected editor with an empty file. When the file is saved, it will be automatically installed by the crontab command.

If you later want to remove your user crontab completely, use crontab with the -r option.

11.6. 在 FreeBSD 使用 rc

Contributed by Tom Rhodes.

從 2002 年起,FreeBSD 整合了 NetBSD 的 rc.d 機制來作為系統服務啟動機制。 可以到 /etc/rc.d 目錄下去看,很多檔案都是基本服務,可以用 start, stoprestart 作為使用時的選項。 舉個例子,可以用下列指令來重新啟動 sshd(8)

# /etc/rc.d/sshd restart

其他服務也是類似作法。當然, 服務通常只要在 rc.conf(5) 內有指定的話,都會在開機時就自動啟動。舉例來說,若要開機時啟動 NAT(Network Address Translation) daemon 的話,只要在 /etc/rc.conf 內加上下列這行即可:

natd_enable="YES"

若原本寫的是 natd_enable="NO" 那麼只要把 NO 改為 YES 就好了。rc scripts 會在下次重開機時,自動載入相關(有相依)的服務,以下我們會講到這部分。

Since the rc.d system is primarily intended to start/stop services at system startup/shutdown time, the standard start, stop and restart options will only perform their action if the appropriate /etc/rc.conf variables are set. For instance the above sshd restart command will only work if sshd_enable is set to YES in /etc/rc.conf. To start, stop or restart a service regardless of the settings in /etc/rc.conf, the commands should be prefixed with force. For instance to restart sshd regardless of the current /etc/rc.conf setting, execute the following command:

# /etc/rc.d/sshd forcerestart

It is easy to check if a service is enabled in /etc/rc.conf by running the appropriate rc.d script with the option rcvar. Thus, an administrator can check that sshd is in fact enabled in /etc/rc.conf by running:

# /etc/rc.d/sshd rcvar
# sshd
$sshd_enable=YES

注意:

The second line (# sshd) is the output from the sshd command, not a root console.

若要檢查服務是否有在運作,可以用 status 選項來查詢。比如:若要確認 sshd 是否真的有啟動的話,那麼打:

# /etc/rc.d/sshd status
sshd is running as pid 433.

In some cases it is also possible to reload a service. This will attempt to send a signal to an individual service, forcing the service to reload its configuration files. In most cases this means sending the service a SIGHUP signal. Support for this feature is not included for every service.

The rc.d system is not only used for network services, it also contributes to most of the system initialization. For instance, consider the bgfsck file. When this script is executed, it will print out the following message:

Starting background file system checks in 60 seconds.

Therefore this file is used for background file system checks, which are done only during system initialization.

Many system services depend on other services to function properly. For example, NIS and other RPC-based services may fail to start until after the rpcbind (portmapper) service has started. To resolve this issue, information about dependencies and other meta-data is included in the comments at the top of each startup script. The rcorder(8) program is then used to parse these comments during system initialization to determine the order in which system services should be invoked to satisfy the dependencies. The following words may be included at the top of each startup file:

  • PROVIDE: Specifies the services this file provides.

  • REQUIRE: Lists services which are required for this service. This file will run after the specified services.

  • BEFORE: Lists services which depend on this service. This file will run before the specified services.

By using this method, an administrator can easily control system services without the hassle of runlevels like some other UNIX® operating systems.

Additional information about the rc.d system can be found in the rc(8) and rc.subr(8) manual pages.

11.7. 設定網路卡

Contributed by Marc Fonvieille.

Nowadays we can not think about a computer without thinking about a network connection. Adding and configuring a network card is a common task for any FreeBSD administrator.

11.7.1. 選擇正確、可用的驅動程式(Driver)

Before you begin, you should know the model of the card you have, the chip it uses, and whether it is a PCI or ISA card. FreeBSD supports a wide variety of both PCI and ISA cards. Check the Hardware Compatibility List for your release to see if your card is supported.

Once you are sure your card is supported, you need to determine the proper driver for the card. /usr/src/sys/conf/NOTES and /usr/src/sys/arch/conf/NOTES will give you the list of network interface drivers with some information about the supported chipsets/cards. If you have doubts about which driver is the correct one, read the manual page of the driver. The manual page will give you more information about the supported hardware and even the possible problems that could occur.

If you own a common card, most of the time you will not have to look very hard for a driver. Drivers for common network cards are present in the GENERIC kernel, so your card should show up during boot, like so:

dc0: <82c169 PNIC 10/100BaseTX> port 0xa000-0xa0ff mem 0xd3800000-0xd38
000ff irq 15 at device 11.0 on pci0
dc0: Ethernet address: 00:a0:cc:da:da:da
miibus0: <MII bus> on dc0
ukphy0: <Generic IEEE 802.3u media interface> on miibus0
ukphy0:  10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto
dc1: <82c169 PNIC 10/100BaseTX> port 0x9800-0x98ff mem 0xd3000000-0xd30
000ff irq 11 at device 12.0 on pci0
dc1: Ethernet address: 00:a0:cc:da:da:db
miibus1: <MII bus> on dc1
ukphy1: <Generic IEEE 802.3u media interface> on miibus1
ukphy1:  10baseT, 10baseT-FDX, 100baseTX, 100baseTX-FDX, auto

In this example, we see that two cards using the dc(4) driver are present on the system.

If the driver for your NIC is not present in GENERIC, you will need to load the proper driver to use your NIC. This may be accomplished in one of two ways:

  • The easiest way is to simply load a kernel module for your network card with kldload(8), or automatically at boot time by adding the appropriate line to the file /boot/loader.conf. Not all NIC drivers are available as modules; notable examples of devices for which modules do not exist are ISA cards.

  • Alternatively, you may statically compile the support for your card into your kernel. Check /usr/src/sys/conf/NOTES, /usr/src/sys/arch/conf/NOTES and the manual page of the driver to know what to add in your kernel configuration file. For more information about recompiling your kernel, please see 章 8, 設定 FreeBSD Kernel. If your card was detected at boot by your kernel (GENERIC) you do not have to build a new kernel.

11.7.1.1. Using Windows® NDIS Drivers

Unfortunately, there are still many vendors that do not provide schematics for their drivers to the open source community because they regard such information as trade secrets. Consequently, the developers of FreeBSD and other operating systems are left two choices: develop the drivers by a long and pain-staking process of reverse engineering or using the existing driver binaries available for the Microsoft® Windows® platforms. Most developers, including those involved with FreeBSD, have taken the latter approach.

Thanks to the contributions of Bill Paul (wpaul), as of FreeBSD 5.3-RELEASE there is native support for the Network Driver Interface Specification (NDIS). The FreeBSD NDISulator (otherwise known as Project Evil) takes a Windows® driver binary and basically tricks it into thinking it is running on Windows®. Because the ndis(4) driver is using a Windows® binary, it is only usable on i386™ and amd64 systems.

注意:

The ndis(4) driver is designed to support mainly PCI, CardBus and PCMCIA devices, USB devices are not yet supported.

In order to use the NDISulator, you need three things:

  1. Kernel sources

  2. Windows® XP driver binary (.SYS extension)

  3. Windows® XP driver configuration file (.INF extension)

Locate the files for your specific card. Generally, they can be found on the included CDs or at the vendors' websites. In the following examples, we will use W32DRIVER.SYS and W32DRIVER.INF.

注意:

You can not use a Windows®/i386 driver with FreeBSD/amd64, you must get a Windows®/amd64 driver to make it work properly.

The next step is to compile the driver binary into a loadable kernel module. To accomplish this, as root, use ndisgen(8):

# ndisgen /path/to/W32DRIVER.INF /path/to/W32DRIVER.SYS

The ndisgen(8) utility is interactive and will prompt for any extra information it requires; it will produce a kernel module in the current directory which can be loaded as follows:

# kldload ./W32DRIVER.ko

In addition to the generated kernel module, you must load the ndis.ko and if_ndis.ko modules. This should be automatically done when you load any module that depends on ndis(4). If you want to load them manually, use the following commands:

# kldload ndis
# kldload if_ndis

The first command loads the NDIS miniport driver wrapper, the second loads the actual network interface.

Now, check dmesg(8) to see if there were any errors loading. If all went well, you should get output resembling the following:

ndis0: <Wireless-G PCI Adapter> mem 0xf4100000-0xf4101fff irq 3 at device 8.0 on pci1
ndis0: NDIS API version: 5.0
ndis0: Ethernet address: 0a:b1:2c:d3:4e:f5
ndis0: 11b rates: 1Mbps 2Mbps 5.5Mbps 11Mbps
ndis0: 11g rates: 6Mbps 9Mbps 12Mbps 18Mbps 36Mbps 48Mbps 54Mbps

From here you can treat the ndis0 device like any other network interface (e.g., dc0).

You can configure the system to load the NDIS modules at boot time in the same way as with any other module. First, copy the generated module, W32DRIVER.ko, to the /boot/modules directory. Then, add the following line to /boot/loader.conf:

W32DRIVER_load="YES"

11.7.2. 設定網路卡

Once the right driver is loaded for the network card, the card needs to be configured. As with many other things, the network card may have been configured at installation time by sysinstall.

To display the configuration for the network interfaces on your system, enter the following command:

% ifconfig
dc0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
        inet 192.168.1.3 netmask 0xffffff00 broadcast 192.168.1.255
        ether 00:a0:cc:da:da:da
        media: Ethernet autoselect (100baseTX <full-duplex>)
        status: active
dc1: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 1500
        inet 10.0.0.1 netmask 0xffffff00 broadcast 10.0.0.255
        ether 00:a0:cc:da:da:db
        media: Ethernet 10baseT/UTP
        status: no carrier
lp0: flags=8810<POINTOPOINT,SIMPLEX,MULTICAST> mtu 1500
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
        inet 127.0.0.1 netmask 0xff000000
tun0: flags=8010<POINTOPOINT,MULTICAST> mtu 1500

注意:

Old versions of FreeBSD may require the -a option following ifconfig(8), for more details about the correct syntax of ifconfig(8), please refer to the manual page. Note also that entries concerning IPv6 (