shells, system calls, and signals michael scherger department of computer science kent state...

46
Shells, System Calls, Shells, System Calls, and Signals and Signals Michael Scherger Michael Scherger Department of Computer Department of Computer Science Science Kent State University Kent State University

Upload: calvin-paul

Post on 02-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Shells, System Calls, and Shells, System Calls, and SignalsSignals

Michael SchergerMichael Scherger

Department of Computer ScienceDepartment of Computer Science

Kent State UniversityKent State University

Page 2: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

What is a Shell?What is a Shell?

A shell is a command line interface to the A shell is a command line interface to the operating systemoperating system– Fetch a command from the user and execute Fetch a command from the user and execute

the commandthe commandSometimes the commands are built-in to the shellSometimes the commands are built-in to the shellOther times the commands are external system Other times the commands are external system programs or user programsprograms or user programs

There are lots of different shells available There are lots of different shells available in UNIXin UNIX

Page 3: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Bourne ShellBourne Shell

Historically the Historically the shsh language was the first language was the first to be created and goes under the name of to be created and goes under the name of The Bourne ShellThe Bourne Shell

It has a very compact syntax which makes It has a very compact syntax which makes it obtuse for novice users but very efficient it obtuse for novice users but very efficient when used by expertswhen used by experts

It also contains some powerful constructs It also contains some powerful constructs built inbuilt in

Page 4: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Bourne ShellBourne Shell

On UNIX systems, most of the scripts On UNIX systems, most of the scripts used to start and configure the operating used to start and configure the operating system are written in the Bourne shellsystem are written in the Bourne shell

It has been around for so long that is It has been around for so long that is virtually bug freevirtually bug free

Page 5: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

C ShellC Shell

The C Shell (csh)The C Shell (csh)– Similar syntactical structures to the C Similar syntactical structures to the C

languagelanguage

The UNIX man pages contain almost twice The UNIX man pages contain almost twice as much information for the C Shell as the as much information for the C Shell as the pages for the Bourne Shell, leading most pages for the Bourne Shell, leading most users to believe that it is twice as goodusers to believe that it is twice as good

Page 6: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

C ShellC Shell

Actually, there are several compromises Actually, there are several compromises within the C Shell which makes using the within the C Shell which makes using the language for serious work difficultlanguage for serious work difficult

(Check the list of bugs at the end of the (Check the list of bugs at the end of the man pages!).man pages!).

Page 7: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

C ShellC Shell

The real reason why the C Shell is so The real reason why the C Shell is so popular is that it is usually selected as the popular is that it is usually selected as the default login shell for most usersdefault login shell for most users

The features that guarantee its continued The features that guarantee its continued use in this arena are aliases and history use in this arena are aliases and history listslists

Page 8: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

tcsh – An Enhanced C Shelltcsh – An Enhanced C Shell

An enhanced but completely compatible An enhanced but completely compatible version of the Berkeley UNIX C Shell, cshversion of the Berkeley UNIX C Shell, csh

It is a command language interpreter It is a command language interpreter usable both as an interactive login shell usable both as an interactive login shell and a shell script command processorand a shell script command processor

Uses a C-like syntaxUses a C-like syntax

Page 9: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

tcsh – An Enhanced C Shelltcsh – An Enhanced C Shell

It includes:It includes:– Command-line editorCommand-line editor– Programmable word completionProgrammable word completion– Spelling correctionSpelling correction– History mechanismHistory mechanism– Job controlJob control

Page 10: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

BASHBASH

GNU Bourne Again ShellGNU Bourne Again ShellA complete implementation of the IEEE A complete implementation of the IEEE POSIX.2 and Open Group Shell POSIX.2 and Open Group Shell specificaiton with…specificaiton with…– Interactive command line editingInteractive command line editing– Job control on architectures that support itJob control on architectures that support it– Csh-like features such as history substitution Csh-like features such as history substitution

and brace expansionand brace expansion– ……and a slew of other featuresand a slew of other features

Page 11: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Korne ShellKorne Shell

The The kshksh was made famous by IBM’s AIX was made famous by IBM’s AIX version of UNIXversion of UNIX

The Korne Shell can be thought of as a The Korne Shell can be thought of as a superset of the Borne Shell as it contains superset of the Borne Shell as it contains the whole of the Borne Shell world within the whole of the Borne Shell world within its own syntax rulesits own syntax rules

Page 12: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Processes and the CWDProcesses and the CWD

Every process runs Every process runs in a directory– The attribute is called the “current working directory”

(cwd)

Finding the CWDchar *getcwd( char *buf, size_t size );

– Returns a string that contains the absolute pathname of the current working directory

There are functions that can be used to change the current working directory (chdir)

Page 13: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Other Process AttributesOther Process Attributes

Getting the process id numberGetting the process id number

#include <unistd.h>#include <unistd.h>pid_t getpid( void );pid_t getpid( void );

Getting the group id numberGetting the group id numbergid_t getgid( void );gid_t getgid( void );

Getting the real user ID of a processGetting the real user ID of a processuid_t getuid( void );uid_t getuid( void );

Page 14: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Creating a ProcessCreating a Process

The only way to create a new process is to The only way to create a new process is to issue the fork() system callissue the fork() system call

Fork() splits the current process into 2 Fork() splits the current process into 2 processes, one is called the parent and processes, one is called the parent and the other is called the childthe other is called the child

Page 15: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Parent and Child ProcessesParent and Child Processes

The child process is a copy of the parent The child process is a copy of the parent processprocess

Same programSame program

Same place in the programSame place in the program– Almost….Almost….

The child process get a new process IDThe child process get a new process ID

Page 16: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Process Inheritance Process Inheritance

The child process inherits many attributes The child process inherits many attributes from the parent including…from the parent including…– Current working directoryCurrent working directory– User idUser id– Group idGroup id

Page 17: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

The fork() system callThe fork() system call

#include <unistd.h>#include <unistd.h>

Pid_t fork( void );Pid_t fork( void );

fork() returns a process id (small unsigned returns a process id (small unsigned integer)integer)

fork()fork() returns twice!!!!!!! returns twice!!!!!!!– In the parent process, fork returns the id of In the parent process, fork returns the id of

the child processthe child process– In the child, fork returns a 0In the child, fork returns a 0

Page 18: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

ExampleExample

#include <unistd.h>#include <unistd.h>#include <iostream>#include <iostream>using namespace std;using namespace std;

int main( int argc, char *argv[] )int main( int argc, char *argv[] ){{ if( fork() )if( fork() ) cout << "I am the parent" << endl;cout << "I am the parent" << endl; elseelse cout << "I am the child" << endl;cout << "I am the child" << endl; return( 0 );return( 0 );}}

Page 19: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Bad Example (don’t do this)Bad Example (don’t do this)

#include <unistd.h> // This is called a#include <unistd.h> // This is called a#include <iostream> // fork bomb!!!!!#include <iostream> // fork bomb!!!!!using namespace std; // please don’t do this using namespace std; // please don’t do this

int main( int argc, char *argv[] )int main( int argc, char *argv[] ){{ while( fork() )while( fork() ) cout << "I am the parent" << endl;cout << "I am the parent" << endl; cout << "I am the child" << endl;cout << "I am the child" << endl; return( 0 );return( 0 );}}

Page 20: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Switching ProgramsSwitching Programs

fork() is the only way to create a new fork() is the only way to create a new processprocess

This would be almost useless if there was This would be almost useless if there was not a way to switch what not a way to switch what programprogram is is associated with a processassociated with a process

The exec() system call is used to start a The exec() system call is used to start a new programnew program

Page 21: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

exec()exec()

There are actually a number of exec There are actually a number of exec functionsfunctions– execlp, execl, execle, execvp, execv, execveexeclp, execl, execle, execvp, execv, execve

The difference between these functions is The difference between these functions is the parametersthe parameters– How the new program is identified and some How the new program is identified and some

attributes that should be setattributes that should be set

Page 22: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

The exec FamilyThe exec Family

When you call a member of the exec When you call a member of the exec family, you give it the pathname of the family, you give it the pathname of the executable file that you want to runexecutable file that you want to run

If all goes well, exec will never return!!!If all goes well, exec will never return!!!

The process becomes the new program!!!The process becomes the new program!!!

Page 23: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Execl()Execl()

int execl(int execl( char *path,char *path,char *arg0,char *arg0,char *arg1, char *arg1, ……,,char *argN,char *argN,(char *) 0);(char *) 0);

execl( “/home/mscherge/bin/foobar”, execl( “/home/mscherge/bin/foobar”, “alpha”, “beta”, NULL );“alpha”, “beta”, NULL );

Page 24: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

A Complete execl ExampleA Complete execl Example#include <unistd.h>#include <unistd.h>#include <iostream>#include <iostream>using namespace std;using namespace std;

int main( int argc, char *argv[] )int main( int argc, char *argv[] ){{

char buf[ 1000 ];char buf[ 1000 ];

cout << "Here are the files in " << getcwd( buf, 1000 ) << endl;cout << "Here are the files in " << getcwd( buf, 1000 ) << endl;

execl( "/bin/ls", "ls", "-al", NULL );execl( "/bin/ls", "ls", "-al", NULL );

cout << "If all goes well, this line will not be printed!!!" << cout << "If all goes well, this line will not be printed!!!" << endl;endl;

return( 0 );return( 0 );}}

Page 25: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

fork() and exec() Togetherfork() and exec() Together

The following program does the following:The following program does the following:– fork() – results in 2 processesfork() – results in 2 processes– Parent prints out it’s PID and waits for child Parent prints out it’s PID and waits for child

process to finish (to exit)process to finish (to exit)– Child process prints out it’s PID and then Child process prints out it’s PID and then

exec() “ls” and then exitsexec() “ls” and then exits

Page 26: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

execandfork.cpp (1)execandfork.cpp (1)

#include <unistd.h> // exec, fork, getpid#include <unistd.h> // exec, fork, getpid

#include <iostream> // cout#include <iostream> // cout

#include <sys/types.h> // needed for wait#include <sys/types.h> // needed for wait

#include <sys/wait.h> // wait()#include <sys/wait.h> // wait()

using namespace std;using namespace std;

Page 27: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

execandfork.cpp (2)execandfork.cpp (2)void child( void )void child( void ){{ int pid = getpid();int pid = getpid();

cout << "CHILD: Child process PID is " << pid << endl;cout << "CHILD: Child process PID is " << pid << endl; cout << "CHILD: Child process now ready to exec ls" << endl;cout << "CHILD: Child process now ready to exec ls" << endl;

execl( "/bin/ls", "ls", NULL );execl( "/bin/ls", "ls", NULL );}}

Page 28: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

execandfork.cpp (3)execandfork.cpp (3)void parent( void )void parent( void ){{ int pid = getpid();int pid = getpid(); int stat;int stat;

cout << "PARENT: Parent process PID is " << pid << endl;cout << "PARENT: Parent process PID is " << pid << endl; cout << "PARENT: Parent waiting for child" << endl;cout << "PARENT: Parent waiting for child" << endl; wait( &stat );wait( &stat ); cout << "PARENT: Child is done. Parent returning" << endl;cout << "PARENT: Child is done. Parent returning" << endl;}}

Page 29: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

execandfork.cpp (4)execandfork.cpp (4)int main( int argc, char *argv[] )int main( int argc, char *argv[] ){{

cout << "MAIN: Starting fork system call" << endl;cout << "MAIN: Starting fork system call" << endl;

if( fork() )if( fork() ) parent();parent(); elseelse child();child();

cout << "MAIN: Done" << endl;cout << "MAIN: Done" << endl;

return( 0 );return( 0 );}}

Page 30: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

execandfork.cpp (output)execandfork.cpp (output)[neptune.cs.kent.edu] {58}% a.out[neptune.cs.kent.edu] {58}% a.outMAIN: Starting fork system callMAIN: Starting fork system callCHILD: Child process PID is 32557CHILD: Child process PID is 32557CHILD: Child process now ready to exec lsCHILD: Child process now ready to exec lsPARENT: Parent process PID is 32556PARENT: Parent process PID is 32556PARENT: Parent waiting for childPARENT: Parent waiting for childa.out lowcost_DB_NOW.pdf Project 1.pdfa.out lowcost_DB_NOW.pdf Project 1.pdfasc mail public_htmlasc mail public_htmlBackup MASCBackup MASC Software Softwarebin MPISpawn2bin MPISpawn2 ZephyrDemo ZephyrDemohybrid_parallel_system.pdf Parallaxis hybrid_parallel_system.pdf Parallaxis icp_fall2004_prj4.txt Pictures icp_fall2004_prj4.txt Pictures PARENT: Child is done. Parent returningPARENT: Child is done. Parent returningMAIN: DoneMAIN: Done/.automount/b2/users/cs/grad/mscherge/.automount/b2/users/cs/grad/mscherge[neptune.cs.kent.edu] {59}% [neptune.cs.kent.edu] {59}%

Page 31: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

A More Concise ExampleA More Concise Exampleint main()int main(){{

Pid_t pid;Pid_t pid;/* fork another process *//* fork another process */pid = fork();pid = fork();if (pid < 0) { /* error occurred */if (pid < 0) { /* error occurred */

fprintf(stderr, "Fork Failed");fprintf(stderr, "Fork Failed");exit(-1);exit(-1);

}}else if (pid == 0) { /* child process */else if (pid == 0) { /* child process */

execlp("/bin/ls", "ls", NULL);execlp("/bin/ls", "ls", NULL);}}else { /* parent process */else { /* parent process */

/* parent will wait for the child to complete *//* parent will wait for the child to complete */wait (NULL);wait (NULL);printf ("Child Complete");printf ("Child Complete");exit(0);exit(0);

}}}}

Page 32: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

System Calls for Files and System Calls for Files and DirectoriesDirectories

CALLCALL DescriptionDescription

fd = open( name, how )fd = open( name, how ) Open a file for reading and/or writingOpen a file for reading and/or writing

s = close( fd ) s = close( fd ) Close and open fileClose and open file

n = read( fd, buffer, size )n = read( fd, buffer, size ) Read data from a file into a bufferRead data from a file into a buffer

n = write( fd, buffer, size )n = write( fd, buffer, size ) Write data from a buffer into a fileWrite data from a buffer into a file

s = lseek( fd, offset, whence )s = lseek( fd, offset, whence ) Move the “current” pointer for a fileMove the “current” pointer for a file

s = stat( name, &buffer )s = stat( name, &buffer ) Get a file’s status information( in buffer )Get a file’s status information( in buffer )

s = mkdir( name, mode )s = mkdir( name, mode ) Create a new directoryCreate a new directory

s = rmdir( name )s = rmdir( name ) Remove a directory (must be empty)Remove a directory (must be empty)

s = link( name1, name2 )s = link( name1, name2 ) Create a new entry (name2) that points to Create a new entry (name2) that points to the same object as name1the same object as name1

s = unlink( name )s = unlink( name ) Remove the name as a link to an object Remove the name as a link to an object (deletes the object if name was the only link (deletes the object if name was the only link to it)to it)

Page 33: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

More System CallsMore System Calls

CallCall DescriptionDescription

pid = fork()pid = fork() Create a child process identical to the Create a child process identical to the parentparent

pid = waitpid( pid, &statloc, options )pid = waitpid( pid, &statloc, options ) Wait for a child to terminateWait for a child to terminate

s = execve( name, argv, environp )s = execve( name, argv, environp ) Replace a process’ core imageReplace a process’ core image

exit( status )exit( status ) Terminate process execution and return Terminate process execution and return statusstatus

s = chdir( dirname )s = chdir( dirname ) Change the working directoryChange the working directory

s = chmod( name, mode )s = chmod( name, mode ) Change a file’s protection bitsChange a file’s protection bits

s = kill( pid, signal )s = kill( pid, signal ) Send a signal to a processSend a signal to a process

seconds = time( &seconds )seconds = time( &seconds ) Get the elapsed time since January 1, 1970Get the elapsed time since January 1, 1970

Page 34: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

A Simple ShellA Simple Shell

while( true )while( true ) // repeat forever// repeat forever

{{

type_prompt();type_prompt(); // display prompt// display prompt

read_command( command, parameters );read_command( command, parameters ); // input from terminal// input from terminal

if( fork() != 0 )if( fork() != 0 ) // fork off child process// fork off child process

{{ // parent code// parent code

waitpid( -1, &status, 0 );waitpid( -1, &status, 0 ); // wait for child to exit// wait for child to exit

}}

elseelse // child code// child code

{{

execve( command, parameters, 0 );execve( command, parameters, 0 ); // execute command// execute command

}}

}}

Page 35: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Signaling ProcessesSignaling ProcessesSignalSignal– A signal is a notification to a process that an event has A signal is a notification to a process that an event has

occurred. Signals are sometimes called “software interrupts”.occurred. Signals are sometimes called “software interrupts”.

Features of SignalFeatures of Signal– Signal usually occur asynchronously.Signal usually occur asynchronously.– The process does not know ahead of time exactly when a The process does not know ahead of time exactly when a

signal will occur.signal will occur.– Signal can be sent by one process to another process (or to Signal can be sent by one process to another process (or to

itself) or by the kernel to a process.itself) or by the kernel to a process.

Page 36: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Sources for Generating SignalsSources for Generating SignalsHardwareHardware– A process attempts to access addresses outside its A process attempts to access addresses outside its

own address space.own address space.– Divides by zero.Divides by zero.

KernelKernel– Notifying the process that an I/O device for which it Notifying the process that an I/O device for which it

has been waiting is available.has been waiting is available.

Other ProcessesOther Processes– A child process notifying its parent process that it A child process notifying its parent process that it

has terminated.has terminated.

UserUser– Pressing keyboard sequences that generate a quit, Pressing keyboard sequences that generate a quit,

interrupt or stop signal.interrupt or stop signal.

Page 37: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Three Courses of Action Three Courses of Action Process that receives a signal can take one of Process that receives a signal can take one of three action:three action:– Perform the system-specified default for the signalPerform the system-specified default for the signal

notify the parent process that it is terminating;notify the parent process that it is terminating;generate a core file;generate a core file;

– (a file containing the current memory image of the process)(a file containing the current memory image of the process)

terminate.terminate.

– Ignore the signalIgnore the signalA process can do ignoring with all signal but two special A process can do ignoring with all signal but two special signals: SIGSTOP and SIGKILL.signals: SIGSTOP and SIGKILL.

– Catch the Signal (Trapping)Catch the Signal (Trapping)When a process catches a signal, except SIGSTOP and When a process catches a signal, except SIGSTOP and SIGKILL, it invokes a special signal handing routine.SIGKILL, it invokes a special signal handing routine.

Page 38: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

POSIX-Defined Signals (1)POSIX-Defined Signals (1)SIGALRM: Alarm timer time-out. Generated by SIGALRM: Alarm timer time-out. Generated by alarm( ) alarm( ) API.API.SIGABRT: Abort process execution. Generated bySIGABRT: Abort process execution. Generated by abort( ) abort( ) API.API.SIGFPE: Illegal mathematical operation.SIGFPE: Illegal mathematical operation.SIGHUP: Controlling terminal hang-up.SIGHUP: Controlling terminal hang-up.SIGILL: Execution of an illegal machine instruction.SIGILL: Execution of an illegal machine instruction.SIGINT: Process interruption. SIGINT: Process interruption. – Can be generated by Can be generated by <Delete> or <ctrl_C> <Delete> or <ctrl_C> keys.keys.

SIGKILL: Sure kill a process. Can be generated bySIGKILL: Sure kill a process. Can be generated by– ““killkill -9 <process_id -9 <process_id>“ command.>“ command.

SIGPIPE: Illegal write to a pipe.SIGPIPE: Illegal write to a pipe.SIGQUIT: Process quit. Generated by SIGQUIT: Process quit. Generated by <crtl_\> <crtl_\> keys.keys.SIGSEGV: Segmentation fault. generated by de-referencing a NULL SIGSEGV: Segmentation fault. generated by de-referencing a NULL pointer.pointer.

Page 39: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

POSIX-Defined Signals (2)POSIX-Defined Signals (2)SIGTERM: process termination. Can be generated bySIGTERM: process termination. Can be generated by– ““killkill <process_id>” <process_id>” command.command.

SIGUSR1: Reserved to be defined by user.SIGUSR1: Reserved to be defined by user.SIGUSR2: Reserved to be defined by user.SIGUSR2: Reserved to be defined by user.SIGCHLD: Sent to a parent process when its child SIGCHLD: Sent to a parent process when its child process has terminated.process has terminated.SIGCONT: Resume execution of a stopped process.SIGCONT: Resume execution of a stopped process.SIGSTOP: Stop a process execution.SIGSTOP: Stop a process execution.SIGTTIN: Stop a background process when it tries to SIGTTIN: Stop a background process when it tries to read from its controlling terminal.read from its controlling terminal.SIGTSTP: Stop a process execution by the control_Z SIGTSTP: Stop a process execution by the control_Z keys.keys.SIGTTOUT: Stop a background process when it tries to SIGTTOUT: Stop a background process when it tries to write to its controlling terminal.write to its controlling terminal.

Page 40: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Sending SignalsSending Signals

You may send signals to a process connected to You may send signals to a process connected to your terminal by typingyour terminal by typing– ^C^C SIGINTSIGINT terminate executionterminate execution– ^\^\ SIGQUITSIGQUIT terminate and core dumpterminate and core dump– ^Z^Z SIGSTOPSIGSTOP suspend for latersuspend for later

The terminal driver is a program that processes The terminal driver is a program that processes I/O to the terminal can detect these special I/O to the terminal can detect these special character sequences and send the appropriate character sequences and send the appropriate signal to your interactive shell.signal to your interactive shell.The shell in turn generates an appropriate signal The shell in turn generates an appropriate signal to the foreground process.to the foreground process.

Page 41: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

KillKillThe user can use the csh built-in kill command The user can use the csh built-in kill command or use regular UNIX kill command to send a or use regular UNIX kill command to send a specific signal to a named process.specific signal to a named process.– % kill [-sig] process% kill [-sig] process

If no signal is specified, then SIGTERM (15)(terminate) is If no signal is specified, then SIGTERM (15)(terminate) is assumedassumed

In C/C++ the system call isIn C/C++ the system call is– #include <signal.h>#include <signal.h>– int kill( int pid, int sig_id );int kill( int pid, int sig_id );

– Return values: Success = 0, Failure = -1, Sets Return values: Success = 0, Failure = -1, Sets errno…YESerrno…YES

Page 42: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Signal Delivery and ProcessingSignal Delivery and Processing

When an interrupt or event causes a When an interrupt or event causes a signal to occur, the signal is added to a set signal to occur, the signal is added to a set of signals that are waiting for delivery to a of signals that are waiting for delivery to a process.process.

Signals are delivered to a process in a Signals are delivered to a process in a manner similar to hardware interrupts.manner similar to hardware interrupts.

Page 43: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Signal DeliverySignal Delivery

If the signal is not currently blocked by the process, it is If the signal is not currently blocked by the process, it is delivered to the process following these steps:delivered to the process following these steps:– The same signal is blocked from further occurrence until delivery The same signal is blocked from further occurrence until delivery

and processing are finishedand processing are finished– The current process context is saved and a new one builtThe current process context is saved and a new one built– A handler function associated with the signal is calledA handler function associated with the signal is called– If the handler function returns, then the process resumes If the handler function returns, then the process resumes

execution from the point of interrupt, with its saved context execution from the point of interrupt, with its saved context restored. Among other things, the signal mask is restored.restored. Among other things, the signal mask is restored.

Signals have the same prioritySignals have the same priority– But processes can block listening to specific signals via a signal But processes can block listening to specific signals via a signal

maskmask

Page 44: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Signal TrappingSignal Trapping

The system call signal() is used to trap The system call signal() is used to trap signalssignals– #include <signal.h>#include <signal.h>– signal( int sig_id, void * handler() );signal( int sig_id, void * handler() );

Example: Write a C++ program to count Example: Write a C++ program to count the number of times CTRL-C is pressed at the number of times CTRL-C is pressed at the terminalthe terminal– cc_counter.cppcc_counter.cpp

Page 45: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

Signal TrappingSignal Trapping

The system call signal() is used to trap The system call signal() is used to trap signalssignals– #include <signal.h>#include <signal.h>– signal( int sig_id, void * handler() );signal( int sig_id, void * handler() );

Example: Write a C++ program to count Example: Write a C++ program to count the number of times CTRL-C is pressed at the number of times CTRL-C is pressed at the terminalthe terminal– cc_counter.cppcc_counter.cpp

Page 46: Shells, System Calls, and Signals Michael Scherger Department of Computer Science Kent State University

AlarmsAlarmsFunctionFunction– The The alarm alarm API requests the kernel to send the SIGALRM API requests the kernel to send the SIGALRM

signal after a certain number of real clock seconds.signal after a certain number of real clock seconds.– #include #include <signal.h><signal.h>– int alarm( unsigned int time_interval); int alarm( unsigned int time_interval); – Return:Return:

Success: the number of CPU seconds left in the process timer; Success: the number of CPU seconds left in the process timer; Failure: -1; Sets errno: YesFailure: -1; Sets errno: Yes

– ArgumentArgumenttime_intervaltime_interval: the number of CPU seconds elapse time. After : the number of CPU seconds elapse time. After which the kernel will send the SIGALRM signal to the calling which the kernel will send the SIGALRM signal to the calling process.process.

Example: Write a C++ program to set an alarm for Example: Write a C++ program to set an alarm for signal 5 seconds after process startup and trap the signal 5 seconds after process startup and trap the alarm signal.alarm signal.– alarmer.cppalarmer.cpp