3,4 Signal Hand Lin

Embed Size (px)

Citation preview

  • 8/2/2019 3,4 Signal Hand Lin'

    1/41

    VI and Emac Editors in LinuxUsing Text Editors in Linux

    Vi:Vi is often the default editor that pops up when you're ready to write an e-mail message or when you're posting a News message. Vi is complicatedand seems difficult to learn at first. However, it is often the default for Unixand Linux systems. This chapter explains the use of the Vi editor.

    Pico:Pico is a fairly simple text editor that provides straight-forward options andeasy-to-use commands. Although some programmers have frowned at

    Pico's simplicity and limited options, most folks find that it provideseverything necessary to write long documents with minimal hassles.However, Pico is not very good when manipulating certain types of files suchas making changes to .cgi files etc.

    Emacs:Emacs falls somewhere between the straightforward Pico and thecomplicated Vi. Unlike Vi, you don't need to switch between modes toperform basic text editing functions. Sadly, the vast set of powerfulcommands themselves are difficult to remember. The Emacs link includes

    basic information on Emacs for situations where you may encounter it or forthose who use it on an occasional basis.

    1) Vi Editor

    Start the Vi editor by typing vi at the prompt. Typing vi followed by a filename will automatically name the file so you don't have to worry about it

    later.

    On a number of other occasions programs use Vi for text editing. When youpost to a News group or send e-mail, the system may default to Vi. How doyou know when you're in Vi and when you can use Vi commands?

    Vi has two modes: Command mode that lets you use commands to edit,save, or quit; and Text mode that lets you type. If you attempt to do

    http://www.reallylinux.com/docs/editors/editor.shtml#Vi%20Editorhttp://www.reallylinux.com/docs/editors/editor.shtml#Vi%20Editorhttp://www.reallylinux.com/docs/editors/editor.shtml#Pico%20Editorhttp://www.reallylinux.com/docs/editors/editor.shtml#Pico%20Editorhttp://www.reallylinux.com/docs/editors/editor.shtml#Emacs%20Editorhttp://www.reallylinux.com/docs/editors/editor.shtml#Emacs%20Editorhttp://www.reallylinux.com/docs/editors/editor.shtml#Emacs%20Editorhttp://www.reallylinux.com/docs/editors/editor.shtml#Pico%20Editorhttp://www.reallylinux.com/docs/editors/editor.shtml#Vi%20Editor
  • 8/2/2019 3,4 Signal Hand Lin'

    2/41

    something in the wrong mode, the system beeps furiously at you until youeither stop pressing keys or scream (the louder the scream the more beepsyou muffle).

    Use the Esc key to change from one mode to the other.

    Simple Example of Using Vi:

    Vi starts in the Command mode. To switch to text mode press i.Type out your text. To make corrections, move to a location in your text, or

    save your file, switch to the Command mode by pressing Esc.In command mode you may edit, save, or exit (see Command Mode below

    for details).To switch back to Text mode, type i again. Getting the hang of switching

    between modes may take a while, so be patient with yourself.

    Occasionally, when you're typing quickly, some of your text may seem todisappear. Actually your text is still there, but has become blacked out.This black-out is usually caused by a slow screen update, and Vi is notoriousfor this. Because the information on your screen is coming through yourmodem, it needs to be updated (refreshed) occasionally, or parts of theinformation disappear from your screen. To update your screen'sinformation, hold down the Ctrl key and press l (thats an L not a 1) while inthe Command mode. Do this whenever chunks of your text black-out.

    Text Writing ModeThe Vi editor starts in the Command mode. To switch to the Text mode andbegin typing, press i. If you hear several beeps and you're unable to type,then press i twice to switch to the text mode.

    Command ModePress the Esc key to switch from Text mode to Command mode.

    Moving Around

  • 8/2/2019 3,4 Signal Hand Lin'

    3/41

    Saving and Exiting

    quit Vi without saving anything (you'll lose any changes you madewhen using this command) type: :q!

    save/write the file you're working on without exiting type: :wfollowed by a filename

    save/write your file and quit the vi editor in one step by typing: :wq

    Editing

  • 8/2/2019 3,4 Signal Hand Lin'

    4/41

    Vi Troubleshooting

    Trying to use a commandIf you are trying to use a Move, Save, or Edit command but the command isnot working, switch from Text mode to Command mode by pressing the Esckey.

    If the backspace key doesnt work, then hold down the Ctrl key and pressbackspace.

    Trying to saveIf you get the message No current filename, type :w followed by afilename. The message appears only if a filename has not been specified.If you get the message Is a directory, youre trying to write to a directorynot a file. Use a different name for your file to save it properly.

    Emacs Editor

  • 8/2/2019 3,4 Signal Hand Lin'

    5/41

    Start Emacs text editor by typing emacs at the prompt. Typing emacsfollowed by a file name automatically names the file, so you don't have toworry about it later.

    If youre in a hurry, turn the page for Emacs commands.

    Emacs doesn't require you to switch between modes. However, when usingEmacs, keep in mind these things: it's often necessary to press enter beforereaching the end of a line; all of the commands require you to hold down theCtrl key and press a letter; and messages that appear are usually loadedwith jargon, so if you don't understand them, ignore them.

    Simple Example of Using Emacs:

    At the prompt type: emacsYou see a long and dull message appear on your screen. Start

    typing your document.To save your file, hold down the Ctrl key and press x; then hold down the

    Ctrl key and press w.Beside the Write file: ~/ prompt, type the name of your file and pressenter.

    Ex: Write file: ~/testfile.txtTo quit Emacs, hold down the Ctrl key and press x; then hold down the

    Ctrl key and press c.

    Emacs Commands

  • 8/2/2019 3,4 Signal Hand Lin'

    6/41

    Moving

    Saving and Editing

    Saving

    EditingUsing the movement keys, locate your cursor in the appropriate spot forediting. Besides using the Delete key to delete individual characters, you canuse the following editing commands:

  • 8/2/2019 3,4 Signal Hand Lin'

    7/41

    Emacs Troubleshooting

    Trying to SearchIf there are no other text strings that match the one youve searched for,you see the message: Failing I-search backward: flesch. Re-start yoursearch or stop searching.

    Trying to SaveIf you try to save a file that has the same name as a directory, you see themessage: File /usr/u4/mraiszad/test is a directory.You have to name your file something else.

    Emacs Tutorial?An Emacs tutorial is available on the system. To review the Emacs Tutorial,hold down the Ctrl key and press h; then press t. To quit the tutorial, holdthe Ctrl key and press x; then hold the Ctrl; and press c.

    Refreshing Missing Characters?Occasionally, when you're typing quickly, some of your text may seem todisappear. Actually your text is still there, but has become blacked out.This black out is usually caused by a slow screen update. Because theinformation on your screen is coming through your modem, it needs to be

    updated (refreshed) occasionally, or parts of the information disappear fromyour screen. To update your screen's information, hold down the Ctrl keyand press l. Do this whenever chunks of your text black out.

    --- the end ---

  • 8/2/2019 3,4 Signal Hand Lin'

    8/41

    Process Management in linux

    After the operating system completes hardware initialization, you canexecute an application. This executing application is called a process.It is the operating system's job to manage execution of the

    application. When you execute a program, the operating systemcreates a new process. Many processes can exist simultaneously, butonly one process can actually be executing on a CPU at one time. Theoperating system switches between your processes so quickly that itcan appear that the processes are executing simultaneously. Thisconcept is referred to as time-sharing or multitasking.

    When you exit your program (or it finishes executing), the processterminates, and the operating system manages the termination byreclaiming any resources that were being used.

    Most applications perform some tasks between the time the process iscreated and the time it terminates. To perform these tasks, theprogram makes requests to the operating system, and the operatingsystem responds to the requests and allocates necessary resources tothe program. When an executing process needs to use somehardware, the operating system provides access for the process.

    SynopsisProcess Management describes how to control programs in UNIX includinghow to start a job (program) and how to kill it.

    After completing Process Managementthe user should be able to:

    Describe how UNIX executes a command

    Define the use of processes

    Describe the advantages of background execution

    List three common daemon processes

    Monitor processes with ps and timeDifferentiate between foreground and background processes

    Kill processes

    Prioritize processes

    Tune the UNIX system with ps and sar

  • 8/2/2019 3,4 Signal Hand Lin'

    9/41

    Define and manipulate a crontab

    What is a Process?Introduces processes and shows how UNIX interacts with them.

    Executing and processing commands

    Using processes

    Processing in the background

    Using command pipelines

    Working with daemon processes

    Administering ProcessesExplains how to monitor and control processes.

    Monitoring processes with ps and time

    Using foreground and background processes

    Signaling processes

    Killing processes

    Logging out procedure with background processes

    Prioritizing processes

    Working with process groups

    System tuning with ps and sar

    Scheduling ProcessesDescribes how to schedule processes to run automatically.

    Using at to schedule commands

    Defining and manipulating a crontab

    Using cron for system administration

  • 8/2/2019 3,4 Signal Hand Lin'

    10/41

    When you execute a program on your UNIX system, the system creates aspecial environment for that program. This environment contains everythingneeded for the system to run the program as if no other program wererunning on the system.

    Whenever you issue a command in UNIX, it creates, or starts, a newprocess. When you tried out the ls command to list directory contents, youstarted a process. A process, in simple terms, is an instance of a runningprogram.

    The operating system tracks processes through a five digit ID number knownas the pid or process ID . Each process in the system has a unique pid.

    Pids eventually repeat because all the possible numbers are used up and thenext pid rolls or starts over. At any one time, no two processes with thesame pid exist in the system because it is the pid that UNIX uses to trackeach process.

    Starting a Process:

    When you start a process (run a command), there are two ways you can runit:

    Foreground Processes Background Processes

    Foreground Processes:

    By default, every process that you start runs in the foreground. It gets itsinput from the keyboard and sends its output to the screen.

    You can see this happen with the ls command. If I want to list all the files inmy current directory, I can use the following command:

    [amrood]$ls ch*.doc

    This would display all the files whose name start with ch and ends with .doc:

    ch01-1.doc ch010.doc ch02.doc ch03-2.docch04-1.doc ch040.doc ch05.doc ch06-2.docch01-2.doc ch02-1.doc

  • 8/2/2019 3,4 Signal Hand Lin'

    11/41

    The process runs in the foreground, the output is directed to my screen, andif the ls command wants any input (which it does not), it waits for it fromthe keyboard.

    While a program is running in foreground and taking much time, we cannot

    run any other commands (start any other processes) because prompt wouldnot be available until program finishes its processing and comes out.

    Background Processes:

    A background process runs without being connected to your keyboard. If thebackground process requires any keyboard input, it waits.

    The advantage of running a process in the background is that you can runother commands; you do not have to wait until it completes to start another!

    The simplest way to start a background process is to add an ampersand ( &)at the end of the command.

    [amrood]$ls ch*.doc &

    This would also display all the files whose name start with ch and ends with.doc:

    ch01-1.doc ch010.doc ch02.doc ch03-2.doc

    ch04-1.doc ch040.doc ch05.doc ch06-2.docch01-2.doc ch02-1.doc

    Here if the ls command wants any input (which it does not), it goes into astop state until I move it into the foreground and give it the data from thekeyboard.

    That first line contains information about the background process - the jobnumber and process ID. You need to know the job number to manipulate itbetween background and foreground.

    If you press the Enter key now, you see the following:

    [1] + Done ls ch*.doc &[amrood]$

    The first line tells you that the ls command background process finishessuccessfully. The second is a prompt for another command.

  • 8/2/2019 3,4 Signal Hand Lin'

    12/41

    Listing Running Processes:

    It is easy to see your own processes by running the ps (process status)command as follows:

    [amrood]$psPID TTY TIME CMD18358 ttyp3 00:00:00 sh18361 ttyp3 00:01:31 abiword18789 ttyp3 00:00:00 ps

    One of the most commonly used flags for ps is the -f( f for full) option,which provides more information as shown in the following example:

    [amrood]$ps -f

    UID PID PPID C STIME TTY TIME CMDamrood 6738 3662 0 10:23:03 pts/6 0:00 first_oneamrood 6739 3662 0 10:22:54 pts/6 0:00second_oneamrood 3662 3657 0 08:10:53 pts/6 0:00 -kshamrood 6892 3662 4 10:51:50 pts/6 0:00 ps -f

    Here is the description of all the fileds displayed by ps -f command:

    Column Description

    UID User ID that this process belongs to (the person running it).

    PID Process ID.

    PPID Parent process ID (the ID of the process that started it).

    C CPU utilization of process.

    STIME Process start time.

    TTY Terminal type associated with the process

    TIME CPU time taken by the process.CMD The command that started this process.

    There are other options which can be used along with ps command:

    Option Description

  • 8/2/2019 3,4 Signal Hand Lin'

    13/41

    -a Shows information about all users

    -x Shows information about processes without terminals.

    -u Shows additional information like -f option.

    -e Display extended information.

    Stopping Processes:

    Ending a process can be done in several different ways. Often, from aconsole-based command, sending a CTRL + C keystroke (the defaultinterrupt character) will exit the command. This works when process isrunning in foreground mode.

    If a process is running in background mode then first you would need to get

    its Job ID using pscommand and after that you can use kill command to killthe process as follows:

    [amrood]$ps -fUID PID PPID C STIME TTY TIME CMDamrood 6738 3662 0 10:23:03 pts/6 0:00 first_oneamrood 6739 3662 0 10:22:54 pts/6 0:00second_oneamrood 3662 3657 0 08:10:53 pts/6 0:00 -kshamrood 6892 3662 4 10:51:50 pts/6 0:00 ps -f[amrood]$kill 6738Terminated

    Here kill command would terminate first_one process. If a process ignores aregular kill command, you can use kill -9 followed by the process ID asfollows:

    [amrood]$kill -9 6738Terminated

    Parent and Child Processes:

    Each unix process has two ID numbers assigned to it: Process ID (pid) andParent process ID (ppid). Each user process in the system has a parentprocess.

    Most of the commands that you run have the shell as their parent. Check ps-f example where this commad listed both process ID and parent process ID.

  • 8/2/2019 3,4 Signal Hand Lin'

    14/41

    Zombie and Orphan Processes:

    Normally, when a child process is killed, the parent process is told via aSIGCHLD signal. Then the parent can do some other task or restart a newchild as needed. However, sometimes the parent process is killed before its

    child is killed. In this case, the "parent of all processes," initprocess,becomes the new PPID (parent process ID). Sometime these processes arecalled orphan process.

    When a process is killed, a ps listing may still show the process with a Zstate. This is a zombie, or defunct, process. The process is dead and notbeing used. These processes are different from orphan processes.They arethe processes that has completed execution but still has an entry in theprocess table.

    Daemon Processes:

    Daemons are system-related background processes that often run with thepermissions of root and services requests from other processes.

    A daemon process has no controlling terminal. It cannot open /dev/tty. Ifyou do a "ps -ef" and look at the tty field, all daemons will have a ? for thetty.

    More clearly, a daemon is just a process that runs in the background, usuallywaiting for something to happen that it is capable of working with, like a

    printer daemon is waiting for print commands.

    If you have a program which needs to do long processing then its worth tomake it a daemon and run it in background.

    The top Command:

    The top command is a very useful tool for quickly showing processes sortedby various criteria.

    It is an interactive diagnostic tool that updates frequently and shows

    information about physical and virtual memory, CPU usage, load averages,and your busy processes.

    Here is simple syntax to run top command and to see the statistics of CPUutilization by different processes:

    [amrood]$top

  • 8/2/2019 3,4 Signal Hand Lin'

    15/41

    Job ID Versus Process ID:

    Background and suspended processes are usually manipulated via jobnumber (job ID). This number is different from the process ID and is usedbecause it is shorter.

    In addition, a job can consist of multiple processes running in series or atthe same time, in parallel, so using the job ID is easier than tracking theindividual processes.

    Signal Handling

    In the original Unix systems, when a handler that was established usingsignal() was invoked by the delivery of a signal, the disposition of thesignal would be reset to SIG_DFL, and the system did not block deliveryof further instances of the signal. System V also provides these semantics

    for signal(). This was bad because the signal might be delivered againbefore the handler had a chance to reestablish itself. Furthermore, rapiddeliveries of the same signal could result in recursive invocations of thehandler.

    BSD improved on this situation by changing the semantics of signalhandling (but, unfortunately, silently changed the semantics whenestablishing a handler with sig nal()). On BSD, when a signal handler isinvoked, the signal disposition is not reset, and further instances of thesignal are blocked from being delivered while the handler is executing.

    The situation on Linux is as follows:

    * The kernel's signal() system call provides System V semantics.

    * By default, in glibc 2 and later, the signal() wrapper function does notinvoke the kernel system call. Instead, it calls sigaction(2) using flagsthat supply BSDsemantics. This default behavior is provided as long as the_BSD_SOURCE feature test macro is defined. By default, _BSD_SOURCEis defined; it is also implicitly

    defined if one defines _GNU_SOURCE, and can of course be explicitlydefined.On glibc 2 and later, if the _BSD_SOURCE feature test macro is notdefined, then signal() provides System V semantics. (The default implicitdefinition of_BSD_SOURCE is not provided if one invokes gcc(1) in one of its standardmodes (-std=xxx or -ansi) or defines various other feature testmacros such as

  • 8/2/2019 3,4 Signal Hand Lin'

    16/41

    _POSIX_SOURCE, _XOPEN_SOURCE, or _SVID_SOURCE; seefeature_test_macros(7).)

    * The signal() function in Linux libc4 and libc5 provide System Vsemantics. If one on a libc5 system includes instead of

    , then signal()

    IPC:Interrupts and Signals:

    In this section will look at ways in which two processes can communicate.When a process terminates abnormally it usually tries to send a signalindicating what went wrong. C programs (and UNIX) can trap these fordiagnostics. Also user specified communication can take place in this way.

    Signals are software generated interrupts that are sent to a process when aevent happens. Signals can be synchronously generated by an error in anapplication, such as SIGFPE and SIGSEGV, but most signals areasynchronous. Signals can be posted to a process when the system detectsa software event, such as a user entering an interrupt or stop or a killrequest from another process. Signals can also be come directly from the OSkernel when a hardware event such as a bus error or an illegal instruction isencountered. The system defines a set of signals that can be posted to a

    process. Signal delivery is analogous to hardware interrupts in that a signalcan be blocked from being delivered in the future. Most signals causetermination of the receiving process if no action is taken by the process inresponse to the signal. Some signals stop the receiving process and othersignals can be ignored. Each signal has a default action which is one of thefollowing:

    The signal is discarded after being received The process is terminated after the signal is received A core file is written, then the process is terminated Stop the process after the signal is received

    Each signal defined by the system falls into one of five classes:

    Hardware conditions Software conditions Input/output notification Process control

  • 8/2/2019 3,4 Signal Hand Lin'

    17/41

    Resource controlMacros are defined in header file for common signals.

    These include:

    SIGHUP 1 /* hangup */ SIGINT 2 /* interrupt */

    SIGQUIT 3 /* quit */ SIGILL 4 /* illegal instruction*/

    SIGABRT 6 /* used by abort */ SIGKILL 9 /* hard kill */

    SIGALRM 14 /* alarm clock */

    SIGCONT 19 /* continue a stopped process*/

    SIGCHLD 20 /* to parent on child stop or exit*/

    Signals can be numbered from 0 to 31.

    Sending Signals -- kill(), raise()

    There are two common functions used to send signals

    int kill(int pid, int signal) - a system call that send a signal to a process, pid.If pid is greater than zero, the signal is sent to the process whose process IDis equal to pid. If pid is 0, the signal is sent to all processes, except systemprocesses.

    kill() returns 0 for a successful call, -1 otherwise and sets errno accordingly.

    int raise(int sig) sends the signal sig to the executingprogram. raise() actually uses kill() to send the signal to the executingprogram:

    kill(getpid(), sig);

    There is also a UNIX command called kill that can be used to send signalsfrom the command line - see man pages.

    NOTE: that unless caught or ignored, the kill signal terminates the process.Therefore protection is built into the system.

    Only processes with certain access privileges can be killed off.

  • 8/2/2019 3,4 Signal Hand Lin'

    18/41

    Basic rule: only processes that have the same user can send/receivemessages.

    The SIGKILL signal cannot be caught or ignored and will always terminate aprocess.

    For examplekill(getpid(),SIGINT); would send the interrupt signal to the id ofthe calling process.

    This would have a similar effect to exit() command. Also ctrl-c typed fromthe command sends a SIGINT to the process currently being.

    unsigned int alarm(unsigned int seconds) -- sends the signal SIGALRM to theinvoking process after seconds seconds.

    Signal Handling -- signal()

    An application program can specify a function called a signal handler to beinvoked when a specific signal is received. When a signal handler is invokedon receipt of a signal, it is said to catch the signal. A process can deal with asignal in one of the following ways:

    The process can let the default action happen The process can block the signal (some signals cannot beignored) the process can catch the signal with a handler.

    Signal handlers usually execute on the current stack of the process. This letsthe signal handler return to the point that execution was interrupted in theprocess. This can be changed on a per-signal basis so that a signal handlerexecutes on a special stack. If a process must resume in a different contextthan the interrupted one, it must restore the previous context itself

    Receiving signals is straighforward with the function:

    int (*signal(int sig, void (*func)()))() -- that is to say thefunction signal() will call the func functions if the process receives asignal sig. Signal returns a pointer to function func if successful or it returnsan error to errno and -1 otherwise.

  • 8/2/2019 3,4 Signal Hand Lin'

    19/41

    func() can have three values:

    SIG_DFL

    -- a pointer to a system default function SID_DFL(), which willterminate the process upon receipt of sig.

    SIG_IGN-- a pointer to system ignore function SIG_IGN() which will disregardthe sig action (UNLESS it is SIGKILL).

    A function address

    -- a user specified function.

    SIG_DFL and SIG_IGN are defined in signal.h (standard library) header file.

    Thus to ignore a ctrl-c command from the command line. we could do:

    signal(SIGINT, SIG_IGN);

    TO reset system so that SIGINT causes a termination at any place in ourprogram, we would do:

    signal(SIGINT, SIG_DFL);

    So lets write a program to trap a ctrl-c but not quit on this signal. We have afunction sigproc() that is executed when we trap a ctrl-c. We will also set

    another function to quit the program if it traps the SIGQUIT signal so we canterminate our program:

    #include

    void sigproc(void);

    void quitproc(void);

    main()

    { signal(SIGINT, sigproc);signal(SIGQUIT, quitproc);

    printf(``ctrl-c disabled use ctrl- to quit n'');for(;;); /* infinite loop */}

    void sigproc()

  • 8/2/2019 3,4 Signal Hand Lin'

    20/41

    { signal(SIGINT, sigproc); /* *//* NOTE some versions of UNIX will reset signal to defaultafter each call. So for portability reset signal each time */

    printf(``you have pressed ctrl-c n'');}

    void quitproc()

    { printf(``ctrl- pressed to quit n'');exit(0); /* normal exit status */}

    sig_talk.c -- complete example program

    Let us now write a program that communicates between child and parentprocesses using kill() and signal().

    fork() creates the child process from the parent. The pid can be checked todecide whether it is the child (== 0) or the parent (pid = child process id).

    The parent can then send messages to child using the pid and kill().

    The child picks up these signals with signal() and calls appropriate functions.

    An example of communicating process using signals is sig_talk.c:

    /* sig_talk.c --- Example of how 2 processes can talk *//* to each other using kill() and signal() *//* We will fork() 2 process and let the parent send a few *//* signals to it s child */

    /* cc sig_talk.c -o sig_talk */

    #include #include

    void sighup(); /* routines child will call upon sigtrap */void sigint();void sigquit();

    main()

  • 8/2/2019 3,4 Signal Hand Lin'

    21/41

    { int pid;

    /* get child process */

    if ((pid = fork()) < 0) {

    perror("fork");exit(1);}

    if (pid == 0){ /* child */signal(SIGHUP,sighup); /* set function calls */signal(SIGINT,sigint);signal(SIGQUIT, sigquit);for(;;); /* loop for ever */}else /* parent */{ /* pid hold id of child */printf("\nPARENT: sending SIGHUP\n\n");kill(pid,SIGHUP);sleep(3); /* pause for 3 secs */printf("\nPARENT: sending SIGINT\n\n");kill(pid,SIGINT);sleep(3); /* pause for 3 secs */printf("\nPARENT: sending SIGQUIT\n\n");kill(pid,SIGQUIT);

    sleep(3);}}

    void sighup()

    { signal(SIGHUP,sighup); /* reset signal */printf("CHILD: I have received a SIGHUP\n");}

    void sigint()

    { signal(SIGINT,sigint); /* reset signal */printf("CHILD: I have received a SIGINT\n");}

    void sigquit()

  • 8/2/2019 3,4 Signal Hand Lin'

    22/41

    { printf("My DADDY has Killed me!!!\n");exit(0);}

    Other signal functions

    There are a few other functions defined in signal.h:

    int sighold(int sig) -- adds sig to the calling process's signal mask

    int sigrelse(int sig) -- removes sig from the calling process's signal mask

    int sigignore(int sig) -- sets the disposition of sig to SIG_IGN

    int sigpause(int sig) -- removes sig from the calling process's signal maskand suspends the calling process until a signal is received

    System Calls

    UNIX System Calls

    A system call is just what its name implies -- a request for theoperating system to do something on behalf of the user's program. Thesystem calls are functions used in the kernel itself. To theprogrammer, the system call appears as a normal C function call.However since a system call executes code in the kernel, there must be amechanism to change the mode of a process from user mode to kernelmode.The C compiler uses a predefined library of functions (the C library)

  • 8/2/2019 3,4 Signal Hand Lin'

    23/41

    that have the names of the system calls. The library functionstypically invoke an instruction that changes the process execution modeto kernel mode and causes the kernel to start executing code for systemcalls. The instruction that causes the mode change is often referred toas an "operating system trap" which is a software generated interrupt.

    The library routines execute in user mode, but the system call interfaceis a special case of an interrupt handler. The library functions passthe kernel a unique number per system call in a machine dependent way --either as a parameter to the operating system trap, in a particularregister, or on the stack -- and the kernel thus determines the specificsystem call the user is invoking. In handling the operating systemtrap, the kernel looks up the system call number in a table to find theaddress of the appropriate kernel routine that is the entry point forthe system call and to find the number of parameters the system callexpects. The kernel calculates the (user) address of the firstparameter to the system call by adding (or subtracting, depending on thedirection of stack growth) an offset to the user stack pointer,corresponding to the number of the parameters to the system call.Finally, it copies the user parameters to the "u area" and call theappropriate system call routine. After executing the code for thesystem call, the kernel determines whether there was an error. If so,it adjusts register locations in the saved user register context,typically setting the "carry" bit for the PS (processor status) registerand copying the error number into register 0 location. If there were noerrors in the execution of the system call, the kernel clears the"carry" bit in the PS register and copies the appropriate return values

    from the system call into the locations for registers 0 and 1 in thesaved user register context. When the kernel returns from the operatingsystem trap to user mode, it returns to the library instruction afterthe trap instruction. The library interprets the return values from thekernel and returns a value to the user program.

    UNIX system calls are used to manage the file system, control processes,and to provide interprocess communication. The UNIX system interfaceconsists of about 80 system calls (as UNIX evolves this number willincrease). The following table lists about 40 of the more important

    system call:

    -1-

  • 8/2/2019 3,4 Signal Hand Lin'

    24/41

    Functions Comment

    fork not implemented,use create_process or threads

    wait not implemented, use waitpid

    waitpid can only wait for a given PID, notany child process

    getppid not implemented (meaninglessunder Windows)

    nice not implementedtruncate, ftruncate not implemented

    link, symlink, readlink not implemented (no links underWindows)

    access execute permission X_OK cannot betested, it just tests for readpermission instead

    fchmod not implemented

    chown, fchown not implemented (make no senseon a DOS file system)

    umask not implemented

    set_nonblock, clear_nonblock implemented as dummy functions;use threads instead of non-blockingI/O

    rewinddir not implemented; re-open thedirectory instead

    mkfifo not implemented

    kill, pause not implemented (no inter-processsignals in Windows)

    alarm, times not implementedgetitimer, setitimer not implemented

    getuid, getgid always return 1

    getgid, getegid, getgroups not implemented

    setuid, setgid not implemented

    getpwnam, getpwuid always raise Not_found

  • 8/2/2019 3,4 Signal Hand Lin'

    25/41

    getgrnam, getgrgid always raise Not_found

    type socket_domain thedomains PF_UNIX and PF_INET6 arenot supported; PF_INET is fullysupported

    establish_server not implemented; use threads

    terminal functions (tc*) not implemented

    GENERAL CLASS SPECIFIC CLASS SYSTEM CALL---------------------------------------------------------------------File Structure Creating a Channel creat()Related Calls open()close()Input/Output read()write()Random Access lseek()Channel Duplication dup()

    Aliasing and Removing link()Files unlink()File Status stat()fstat()Access Control access()chmod()chown()umask()Device Control ioctl()---------------------------------------------------------------------Process Related Process Creation and exec()Calls Termination fork()wait()exit()Process Owner and Group getuid()geteuid()getgid()getegid()

    http://caml.inria.fr/pub/docs/manual-ocaml/manual034.html
  • 8/2/2019 3,4 Signal Hand Lin'

    26/41

    Process Identity getpid()getppid()Process Control signal()kill()alarm()

    Change Working Directory chdir()----------------------------------------------------------------------Interprocess Pipelines pipe()Communication Messages msgget()msgsnd()msgrcv()msgctl()Semaphores semget()semop()Shared Memory shmget()shmat()shmdt()----------------------------------------------------------------------

    [NOTE: The system call interface is that aspect of UNIX that haschanged the most since the inception of the UNIX system. Therefore,when you write a software tool, you should protect that tool by puttingsystem calls in other subroutines within your program and then callingonly those subroutines. Should the next version of the UNIX systemchange the syntax and semantics of the system calls you've used, youneed only change your interface routines.]

    -2-

    When a system call discovers and error, it returns -1 and stores thereason the called failed in an external variable named "errno". The"/usr/include/errno.h" file maps these error numbers to manifestconstants, and it these constants that you should use in your programs.

    When a system call returns successfully, it returns something other than

  • 8/2/2019 3,4 Signal Hand Lin'

    27/41

    -1, but it does not clear "errno". "errno" only has meaning directlyafter a system call that returns an error.

    When you use system calls in your programs, you should check the valuereturned by those system calls. Furthermore, when a system call

    discovers an error, you should use the "perror()" subroutine to print adiagnostic message on the standard error file that describes why thesystem call failed. The syntax for "perror()" is:

    void perror(string)char string;

    "perror()" displays the argument string, a colon, and then the errormessage, as directed by "errno", followed by a newline. The output of"perror()" is displayed on "standard error". Typically, the argumentgive to "perror()" is the name of the program that incurred the error,argv[0]. However, when using subroutines and system calls on files, therelated file name might be passed to "perror()".

    There are occasions where you the programmer might wish to maintainmorecontrol over the printing of error messages than "perror()" provides --such as with a formatted screen where the newline printed by "perror()"would destroy the formatting. In this case, you can directly access thesame system external (global) variables that "perror()" uses. They are:

    extern int errno;extern char *sys_errlist[];extern int sys_nerr;

    "errno" has been described above. "sys_errlist" is an array (table) ofpointers to the error message strings. Each message string is nullterminated and does not contain a newline. "sys_nerr" is the number ofmessages in the error message table and is the maximum value "errno" canassume. "errno" is used as the index into the table of error messages.Following are two sample programs that display all of the system error

    messages on standard error.

  • 8/2/2019 3,4 Signal Hand Lin'

    28/41

    -3-

    /* errmsg1.cprint all system error messages using "perror()"*/

    #include

    int main(){

    int i;extern int errno, sys_nerr;

    for (i = 0; i < sys_nerr; ++i){fprintf(stderr, "%3d",i);errno = i;perror(" ");}exit (0);

    }

    /* errmsg2.cprint all system error messages using the global error message table.*/

  • 8/2/2019 3,4 Signal Hand Lin'

    29/41

    #include

    int main(){int i;

    extern int sys_nerr;extern char *sys_errlist[];

    fprintf(stderr,"Here are the current %d error messages:\n\n",sys_nerr);for (i = 0; i < sys_nerr; ++i)fprintf(stderr,"%3d: %s\n", i, sys_errlist[i]);}

    -4-

    Following are some examples in the use of the most often used systemcalls.

    File Structure Related System Calls

  • 8/2/2019 3,4 Signal Hand Lin'

    30/41

  • 8/2/2019 3,4 Signal Hand Lin'

    31/41

    However, if the file does exist, its contents are discarded and the modevalue is ignored. The permissions of the existing file are retained.Following is an example of how to use creat():

    -5-

    /* creat.c */

    #include #include /* defines types used by sys/stat.h */#include /* defines S_IREAD & S_IWRITE */

    int main(){

    int fd;fd = creat("datafile.dat", S_IREAD | S_IWRITE);if (fd == -1)printf("Error in opening datafile.dat\n");else{printf("datafile.dat opened for read/write access\n");printf("datafile.dat is currently empty\n");}close(fd);

    exit (0);}

    The following is a sample of the manifest constants for the modeargument as defined in /usr/include/sys/stat.h:

    #define S_IRWXU 0000700 /* -rwx------ */#define S_IREAD 0000400 /* read permission, owner */

  • 8/2/2019 3,4 Signal Hand Lin'

    32/41

    #define S_IRUSR S_IREAD#define S_IWRITE 0000200 /* write permission, owner */#define S_IWUSR S_IWRITE#define S_IEXEC 0000100 /* execute/search permission, owner */#define S_IXUSR S_IEXEC

    #define S_IRWXG 0000070 /* ----rwx--- */#define S_IRGRP 0000040 /* read permission, group */#define S_IWGRP 0000020 /* write " " */#define S_IXGRP 0000010 /* execute/search " " */#define S_IRWXO 0000007 /* -------rwx */#define S_IROTH 0000004 /* read permission, other */#define S_IWOTH 0000002 /* write " " */#define S_IXOTH 0000001 /* execute/search " " */

    Multiple mode values may be combined by or'ing (using the | operator)the values together as demonstrated in the above sample program.

    -6-

    open()

    Next is the open() system call. open() lets you open a file forreading, writing, or reading and writing.

  • 8/2/2019 3,4 Signal Hand Lin'

    33/41

    The prototype for the open() system call is:

    #include

    int open(file_name, option_flags [, mode])char *file_name;int option_flags, mode;

    where file_name is a pointer to the character string that names thefile, option_flags represent the type of channel, and mode defines thefile's access permissions if the file is being created.

    The allowable option_flags as defined in "/usr/include/fcntl.h" are:

    #define O_RDONLY 0 /* Open the file for reading only */#define O_WRONLY 1 /* Open the file for writing only */#define O_RDWR 2 /* Open the file for both reading and writing*/#define O_NDELAY 04 /* Non-blocking I/O */#define O_APPEND 010 /* append (writes guaranteed at the end) */#define O_CREAT 00400 /*open with file create (uses third open arg) */#define O_TRUNC 01000 /* open with truncation */#define O_EXCL 02000 /* exclusive open */

    Multiple values are combined using the | operator (i.e. bitwise OR).Note: some combinations are mutually exclusive such as: O_RDONLY |

    O_WRONLY and will cause open() to fail. If the O_CREAT flag is used,then a mode argument is required. The mode argument may be specified inthe same manner as in the creat() system call.

  • 8/2/2019 3,4 Signal Hand Lin'

    34/41

    -7-

    Following is an example of how to use open():

    /* open.c */

    #include /* defines options flags */#include /* defines types used by sys/stat.h */#include /* defines S_IREAD & S_IWRITE */

    static char message[] = "Hello, world";

    int main(){int fd;char buffer[80];

    /* open datafile.dat for read/write access (O_RDWR)create datafile.dat if it does not exist (O_CREAT)return error if datafile already exists (O_EXCL)

    permit read/write access to file (S_IWRITE | S_IREAD)*/fd = open("datafile.dat",O_RDWR | O_CREAT | O_EXCL, S_IREAD |S_IWRITE);if (fd != -1){printf("datafile.dat opened for read/write access\n");write(fd, message, sizeof(message));

  • 8/2/2019 3,4 Signal Hand Lin'

    35/41

    lseek(fd, 0L, 0); /* go back to the beginning of the file */if (read(fd, buffer, sizeof(message)) == sizeof(message))printf("\"%s\" was written to datafile.dat\n", buffer);elseprintf("*** error reading datafile.dat ***\n");

    close (fd);}elseprintf("*** datafile.dat already exists ***\n");exit (0);}

  • 8/2/2019 3,4 Signal Hand Lin'

    36/41

    close()

    To close a channel, use the close() system call. The prototype for theclose() system call is:

    int close(file_descriptor)int file_descriptor;

    where file_descriptor identifies a currently open channel. close()fails if file_descriptor does not identify a currently open channel.

    read() write()

    The read() system call does all input and the write() system call doesall output. When used together, they provide all the tools necessary todo input and output sequentially. When used with the lseek() systemcall, they provide all the tools necessary to do input and outputrandomly.

    Both read() and write() take three arguments. Their prototypes are:

    int read(file_descriptor, buffer_pointer, transfer_size)int file_descriptor;char *buffer_pointer;unsigned transfer_size;

    int write(file_descriptor, buffer_pointer, transfer_size)int file_descriptor;

    char *buffer_pointer;unsigned transfer_size;

    where file_descriptor identifies the I/O channel, buffer_pointer pointsto the area in memory where the data is stored for a read() or wherethe data is taken for a write(), and transfer_size defines the maximumnumber of characters transferred between the file and the buffer.read() and write() return the number of bytes transferred.

  • 8/2/2019 3,4 Signal Hand Lin'

    37/41

    There is no limit on transfer_size, but you must make sure it's safe tocopy transfer_size bytes to or from the memory pointed to bybuffer_pointer. A transfer_size of 1 is used to transfer a byte at atime for so-called "unbuffered" input/output. The most efficient value

    for transfer_size is the size of the largest physical record the I/Ochannel is likely to have to handle. Therefore, 1K bytes -- the diskblock size -- is the most efficient general-purpose buffer size for astandard file. However, if you are writing to a terminal, the transferis best handled in lines ending with a newline.

    For an example using read() and write(), see the above example ofopen().

    -9-

    lseek()

    The UNIX system file system treats an ordinary file as a sequence ofbytes. No internal structure is imposed on a file by the operatingsystem. Generally, a file is read or written sequentially -- that is,from beginning to the end of the file. Sometimes sequential reading andwriting is not appropriate. It may be inefficient, for instance, to

    read an entire file just to move to the end of the file to addcharacters. Fortunately, the UNIX system lets you read and writeanywhere in the file. Known as "random access", this capability is madepossible with the lseek() system call. During file I/O, the UNIX systemuses a long integer, also called a File Pointer, to keep track of thenext byte to read or write. This long integer represents the number ofbytes from the beginning of the file to that next character. Randomaccess I/O is achieved by changing the value of this file pointer using

  • 8/2/2019 3,4 Signal Hand Lin'

    38/41

    the lseek() system call.

    The prototype for lseek() is:

    long lseek(file_descriptor, offset, whence)

    int file_descriptor;long offset;int whence;

    where file_descriptor identifies the I/O channel and offset and whencework together to describe how to change the file pointer according tothe following table:

    whence new position------------------------------offset bytes into the filecurrent position in the file plus offsetcurrent end-of-file position plus offset

    If successful, lseek() returns a long integer that defines the new filepointer value measured in bytes from the beginning of the file. Ifunsuccessful, the file position does not change.

    Certain devices are incapable of seeking, namely terminals and thecharacter interface to a tape drive. lseek() does not change the filepointer to these devices.

    -10-

  • 8/2/2019 3,4 Signal Hand Lin'

    39/41

  • 8/2/2019 3,4 Signal Hand Lin'

    40/41

    -11-

    Many UNIX systems have defined manifest constants for use as the"whence" argument of lseek(). The definitions can be found in the"file.h" and/or "unistd.h" include files. For example, the Universityof Maryland's HP-9000 UNIX system has the following definitions:

    from file.h we have:

    #define L_SET 0 /* absolute offset */#define L_INCR 1 /* relative to current offset */#define L_XTND 2 /* relative to end of file */

    and from unistd.h we have:

    #define SEEK_SET 0 /* Set file pointer to "offset" */#define SEEK_CUR 1 /* Set file pointer to current plus "offset" */

  • 8/2/2019 3,4 Signal Hand Lin'

    41/41

    #define SEEK_END 2 /* Set file pointer to EOF plus "offset" */

    The definitions from unistd.h are the most "portable" across UNIX andMS-DOS C compilers.

    dup()

    The dup() system call duplicates an open file descriptor and returns thenew file descriptor. The new file descriptor has the followingproperties in common with the original file descriptor:

    refers to the same open file or pipe.

    has the same file pointer -- that is, both file descriptors share onefile pointer.

    has the same access mode, whether read, write, or read and write.

    The prototype for dup() is:

    int dup(file_descriptor)int file_descriptor;

    where file_descriptor is the file descriptor describing the original I/Ochannel returned by creat(), open(), pipe(), or dup() system calls.

    dup() is guaranteed to return a file descriptor with the lowest integervalue available. It is because of this feature of returning the lowestunused file descriptor available that processes accomplish I/Oredirection. The following example shows standard output redirected toa file through the use of the dup() system call: