Introduction to Linux for Programmers
Course Outline
Base Concepts
A Brief History of Linux
- Proprietary Operating Systems
- Why operating systems were developed in the first place.
- Early standards focused on languages, not system software.
- Proprietary operating systems not an issue until minicomputers emerged.
- State of computing in 1975.
- Origins of Unix
- Major purpose.
- Design philosophy:
- KISS!
- Design parity throughout.
- People act professionally.
- Function and performance goals.
- BSD fuels the growth of Linux.
- State of computing in 1985.
- The POSIX® Standard
- Stands for Portable Operating System Interface.
- Currently managed by IEEE Portable Application Standards Committee (http://www.pasc.org).
- Various Subsets:
- System Interface Standard: IEEE Std 1003.1-1990 (ISO 9945-1:1990).
- System Interface Standard: IEEE Std 1003.1-1996 (ISO 9945-1:1996).
- Real Time Extensions : IEEE Std 1003.1b-1993 and Realtime Technical Corrigenda : IEEE Std 1003.1i-1995.
- Threads Extensions : IEEE Std 1003.1c-1995.
- Shell and Utilities : IEEE Std 1003.2-1992 (ISO/IEC 9945-2:1993).
- Test Methods for 1003.1 : IEEE Std 2003.1-1993.
- Ada Bindings for POSIX : IEEE Std 1003.5-1992.
- The IEEE maintains a team of lawyers (!) who interpret POSIX. See http://www.pasc.org/interps for details.
- Development of Linux
- Richard Stallman, MIT, and the Xerox laser printer (1970).
- Free Software Foundation and HURD (1984).
- Linux Torvalds, Linux, and the "merger" (1990).
- Linux is a POSIX, not Unix, implementation.
- GNU General Public License (GPL) and the Lesser GPL (LGPL).
Internal Structures
- Processes
- Protected memory space.
- Environment variables.
- Parents and children.
- Super and user privileges.
- Kernel and user space.
- Daemons and shells.
- Threads
- Interaction of processes and the scheduler.
- Thread code is run independently by the scheduler.
- All threads share the same memory space as the host process.
- Differences in context switch time.
- File System
- Volumeless tree starting at root.
- Subdirectory structure.
- Inode types and storage:
- Regular or executable file.
- Directory.
- Symbolic link.
- Sockets.
- Named pipe.
- File permission system: user, group, world.
- Virtual File System.
- Device Drivers
- Parity between devices and files.
- Device driver directory.
- Driver is executable code that delivers data back to file system.
- Typically run in kernel space.
Command Shells
- The
login
Process
- User and password collection.
- Authentication and configuration.
- Launching of the command shell.
- Initial configuration script processing.
- Differences for GUI based systems (X Windows).
- Command Shell Primer
- Basic functions of a shell.
- Various types of shells:
/bin/sh
/bin/csh
/bin/ksh
/bin/bash
- Odd shell is the C shell: its scripting language looks like C.
- The base shell
sh
is useful for batch jobs due to low overhead.
- We will focus on
bash
in this course.
- Special Characters
- Variable expansion:
$
- Universal pattern match:
*
- Literal interpretation of next character:
\
- Command line ends here:
;
- Comment follows:
#
- Environment Variable Primer
- Purpose.
- Difference between environment and shell variables.
- Displaying all environment variables:
env | more
- Displaying a specific environment variable:
$<variable name>
- Key Environment Variables
- HOME
- HOSTNAME
- DISPLAY
- MAIL
- PATH
- PWD
- SHELL
- TERM
- USER
Linux User Fundamentals
Command Line Processing
- Parsing a Command Line
- Shell matches paired characters:
' " `
- Performs symbol expansion.
- Breaks resulting command line into word tokens.
- One line processed at a time.
- Backslash used as continuation character:
\
- Semicolon breaks multiple commands on same line:
;
- If no errors, first token loaded and all tokens passed as arguments.
- Exception to above are shell built-in commands.
- Symbol Expansion
- File name expansion:
[<text>]*[<text>]
- Environment variable expansion:
$<variable name>
- Shell command expansion:
`<string>`
- Inhibit file name expansion:
"<string>"
- Inhibit all expansion:
'<string>'
- Class Exercise: Interpreting Shell Expansion.
- Command Formats
- By definition first token, $0, is file loaded (command being executed).
- By convention, subsequent tokens prepended by hyphen are options
- By convention, tokens not starting with a hyphen are parameters
- Commands don't see most special characters after symbol expansion.
- By convention, commands needing a target use the last argument.
- Keyboard Shortcuts
- File name and path completion with the TAB key.
- Command line recall with up and down cursor keys.
- Command line editing with left and right cursor keys, backspace, DEL.
- Running Foreground and Background Jobs
- Commands can be executed in the background by appending an
&
as the last token.
- Foreground jobs can be paused by typing CTRL-Z.
- List all jobs running:
jobs
- Start a paused job in the background:
bg %<job identifier>
- Bring a background or paused job to the foreground:
fg %<job identifier>
Essential Shell Navigation
- Current Directory Concept
- Initially user is placed in home directory.
- Can use change directory command to move within tree:
cd
- Provide relative path as argument.
- No argument places user in $HOME.
- Subdirectories are separated via forward slashes:
/
- A single period indicates current directory and two periods parent.
- Subdirectory paths are relative to current.
- The path must be specified for an executable (
$0
) not in the PATH.
- Programs we write must reference PWD for current directory.
- Listing Subdirectories:
ls
- Long format:
-l
- Single column:
-1
- Turn off directory expansion:
-d
- Turn off filtering and show all files:
-a
- Directory and File Manipulation
- Creating a new subdirectory:
mkdir
- Removing an existing subdirectory, if empty:
rmdir
- Copying files:
cp
- Renaming (moving) files:
mv
- Removing files:
rm
- Forced removal option:
-f
- Recursive removal option:
-r
- Reading and Setting File Permissions
- The permission bit structure:
- Three bits each for user, group, and others.
- One bit each for read, write, execute.
- Additional "sticky" bit
- View permissions with
ls -a
- Set permissions with the
chmod
command:
- Set nine permissions bit by octal sum or symbolic constant.
- Sticky bit must be set by octal sum.
- Change owner with
chown
- Change group with
chgrp
- Linking Files
- Difference between a link and a file.
- Hard versus soft links.
- Advantages of and restrictions on hard links.
- Creating links:
ln [-s] <destination> <alias>
- Pipes and Redirection
- By design, Linux commands use standard system files:
stdin
stdout
stderr
- These can be redirected to other files:
- Redirection of
stdin
is via <
- Redirection of
stdout
is via >
- Redirection of
stderr
is via 2>
- Output of one command can be used as an input via a pipe:
|
- Here is one example:
env | more
- There is no limit to the number of allowed pipes except for system capacity.
- When using pipes or redirection, arrange commands to reduce data at each stage.
System Administration Primer
- On Line Documentation
- Need a clue where to start?
apropos <keyword> | grep "(1)" | more
- Quick reference manual pages:
man <command>
- More in-depth reference material:
info <command>
- Viewing Configuration Information
- Who is logged into the system?
users
and who
- Which machine am I on?
hostname
- What is my current user name?
whoami
- What hardware and operating system am I running on?
uname -a
- How is the file system mapped to disk hardware?
df
- How much free memory does the system have?
free
- What TCP/IP connections are active now?
netstat -t
- Disk Management
- Mounting CDs and hard disks:
mount -<options> <device> <path>
- File systems:
- CD:
-r -t iso9660
- Win 3.x/95/98/ME:
-t vfat
- WinNT/2K/XP:
-t ntfs
- OS/2:
-t hpfs
- Mounting devices at system boot:
/etc/fstab
- Removing CDs:
eject cdrom
- Verifying the file system (DANGEROUS):
fsck -N
- X Windows
- X history and architecture:
- MIT Project Athena.
- Design goal of graphic display over network.
- Client and server defined (different from typical use).
- XFree86 is an open source implementation of X11.
- Configuring remote display:
- The DISPLAY environment variable:
export DISPLAY=<node>:0.0
- Allowing other machines to use a local display:
xhost +<node>
- Fixing installation or other configuration errors:
- Boot the system in text mode (or use CTRL-ALT-F1 if lucky).
- Edit the XFree86 configuration file:
/etc/X11/XF86Config
- Scroll down to the Monitor section
- Delete the offending mode if you know it.
- Delete all modes except 640x480 if you don't.
- Edit a mode or monitor entry if you have a hardware manual and understand the specification.
- Avoiding this error in the first place: generic monitors.
- Opening X apps at a fixed position and size:
-geometery <x>x<y>[+<width>+<height>]
- Stuck Software
- Linux doesn't fail so much as take forever to figure there is a problem!
- System originally designed in days of 300 baud modems, so timeouts are long.
- All processes are assigned an identifier.
- Passing this identifier a signal stops the process.
- Finding the identifier:
- If you know the command name:
ps -e | grep <command>
- To search the running commands:
ps -e | more
- The process identifier is the number in the first column.
- Stopping the process:
- Gracefully:
kill <process identifier>
- With force:
kill -9 <process identifier>
- What does
kill
actually do?
- IP Addresses
- Most computers use dyanamic IP addresses:
- DHCP stands for Dynamic Host Control Protocol
- Automatically assigns an IP address to a node from a server.
- Address may expire at some point in the future.
- Typical small network is 192.168.1.1 - 192.168.1.255
- Sometimes devices need a static IP address:
- Fixed for the device and never expires.
- Printers and servers are example devices for which static makes sense.
- Can be edited with system administration tool.
- Or file in the
/etc/sysconfig/network-scripts
directory.
- The file
/etc/sysconfig/network
controls IP forwarding.
Linux Programming Basics
Configuration and File Management
- Packing and Unpacking Archives
- The .ZIP file format is used on PCs to "bundle" a directory tree.
- Linux uses a command line utiltity for (tape) archives:
tar
- Building archives:
tar -cvf <path>
to create a new archive.
tar -cvfz <path>
to also zip.
tar -uvf <path>
to update an existing archive.
tar -cvfz <path>
to update a zipped archive.
tar
archives and expands relatively at or below the specified path.
- Unpacking archives:
tar -xvf <bundle>
to expand an archive.
tar -xvfz <bundle>
to first unzip the bundle.
- Software Installation
- Obtain the appropriate archive via download or media.
- Create a directory:
- Software supplier should provide guideance.
- If not, consider under
/usr/local
if software for all users.
- Or under
$HOME/bin
for a single user.
- Follow guidance for modifying PATH and LD_LIBRARY_PATH.
- Unpack the archive with
tar -xvf[z] <bundle>
- Look for and run an install script.
- Red Hat Package Manager (RPM)
- Use on Red Hat systems where software supplier provides .rpm file.
- Type
rpm -i <filename>
to launch an install GUI.
- RPM guides choosing installation options.
- RPM automatically checks dependencies and installs software.
- Version Control Systems
- Software products change over the development life cycle.
- In team development, person A may make a change that breaks person B's code.
- Version control systems help by adding a version path to the directory path.
- Typical systems are:
- Source Code Control System.
- Resource Control System.
- Conncurrent Version System.
- ClearCase (proprietary--and the best! ;-}).
- We will discuss version control concepts, but not these systems, in class.
Shell Scripting
- What is a Shell Script?
- Automates typing at the command line.
- Ordinary text files can be given run permission (recall
chmod
).
- In such a case, shell will read lines of text and assume they are commands (recall
stdin
and redirection).
- Thus hundreds or even thousands of commands can be executed by typing one: the name of the script file.
- A Simple Shell Script
# .bashrc
# User specific aliases and functions
alias rm='rm -i'
alias cp='cp -i'
alias mv='mv -i'
# Source global definitions
if [ -f /etc/bashrc ] ; then . /etc/bashrc ; fi
- Command Line Parameters
- During scripting, special environment variables exist to collect command line parameters.
- Positional parameters:
$0
, $1
, $2
, ...
- All parameters:
$*
- All parameters, but qutoed:
$@
- Number of parameters:
#
- Others can be found in the
bash man
page.
- The
if
Statement
- Format:
if <test> ; then <actions> ; [ elif <test> then <actions> ; ] [ else <actions> ; ] fi
- Arguments for the
test
command:
- Logical expressions: raw,
-a
, -o
, !
- Numeric expressions:
-eq
, -ne
, -gt
, -ge
, -lt
, -le
- String expressions:
=
, !=
- File operations:
-f
and others.
- Note
if
and elif
and else
are separate.
- The
for
Statement
- Command format:
for <variable> [ in <arguments> ] ; do <actions> ; done
- Arguments may be hard coded text, shell parameters, environment variables, or anything that resolves to a token.
- The
in
clause is optional and creates a variable expandable with dollar sign.
- The actions execute once for each argument supplied.
- The
while
Statement
- Format:
while <test> do <actions> ; done
- Test is performed.
- If true, actions are executed.
- If false, break out of loop.
- Lather. Rinse. Repeat.
Build Management
- The
make
Command
- Used to automate building (compilation and linking) of software.
- By default uses a file named either
Makefile
or makefile
.
- Inspects file for targets.
- Checks targets for dependencies.
- If a dependency is out of date, executes the associated build command.
- Can use files with other names via the
-f
option.
- Structure of a Makefile
- Environment Variables
- Similar to shell environment variables.
- Whitespace separated list of tokens.
- All associated tokens assigned must be on one statement, usually terminated by end of line.
- Use
\
for line continuation.
- If longer then one character must use parenthesis for expansion.
- Example:
$(CC)
- Recursive and Static Assignment
- Recursive assignment with
=
keeps processing until expansion finishes.
- Static assignment with
:=
only makes one pass through the tokens.
- Use static assignment to initialize a target.
- Use recursive assignment to build on a target.
- If in doubt, use recursive assignment.
- Defining Targets
- Targets are tokens that start in column one and are terminated with a colon.
- Tokens can be assigned to a target like an environment variable.
- These tokens should be relative path names to files, such as source and object.
- Make will execute a target's associated build command if any token is out of date.
- Matched token considered when generating actual command passed to shell.
- Extension matching, for example
.c.o
or .o.a
, can be used as well.
- Defining Build Commands
- Build commands immediately follow line after the target and start with tab.
- Commands must be one logical line long.
- Within a build command, one can use special environment variables.
- Prerequisite token:
$<
- Target:
$@
- Stem:
$*
- Chaining Makefiles
- The
make
command honors an include
directive.
- Files are processed in order listed.
- Normally
make
processes the first target encountered (unless a target is specified).
- This also works with
include
directives: each file is processed using the same target.
- Technique to maintain independent Makefiles at subsystem level that are run at system level.
Copyright ©2003-2006, Left Brained Geeks. All rights reserved.