unix system interface programming part 6.3 – process and signal prepared by xu zhenya(...
TRANSCRIPT
Unix System Interface Unix System Interface ProgrammingProgramming
Part 6.3 – Process and Signal
Prepared by Xu Zhenya( [email protected] )
Draft – Xu Zhenya( 2002/10/01 )
Rev1.0 – Xu Zhenya( 2002/10/10 )
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
AgendaAgenda 1. Process 1. Process
2. Signal2. Signal
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Modeling the Concepts( Relationship )Modeling the Concepts( Relationship )
Controlling Terminal
Process Group
Current
Session
foreground
Background
Process
Parent1
1..n
+BelongTo
1
1..n
Leader
UserGroup
User
euid
11
Supplementary
ruid
saved_euid
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Modeling the Concepts ( Sequence )Modeling the Concepts ( Sequence )
fork()
Parent Child
exec()
exit()abort()
Notification by SIGCHLDZombie
• The parent ignores/catches SIGCHLD.
• The parent = “init”
wait(), waitpid(), wait3(), wait4()
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Process ContextProcess Context
kernel code/data/stack
Memory mapped region for shared libraries
runtime heap (via malloc)
program text (.text)
initialized data (.data)
uninitialized data (.bss)
stack
forbidden
0
%espprocess VM
brk
0xc0
physical memory
process-specific datastructures
(page tables,task and mm structs)
kernel VM
.data.text
p
demand-zero
demand-zero
libc.so
.data.text
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Overview of “Process”Overview of “Process”CATEGORY FUNCTION
NAMEPURPOSE
Basic Primitives
fork(2) Create a new process
exec(2)execl(2)execv(2)execle(2)execve(2)execlp(2)execvp(2)
Execute a program
exit(2)_exit(2)
Terminate a process
wait(2)waitpid(2)wait3(2)wait4(2)
Wait for a child process to stop or terminate
waitid(2) Wait for a child process to change state
priocntl(2) Control process scheduler
nice(2) Change priority of a process
pause(2) Suspend process until signal
getcontext(2)setcontext(2)
Get and set current user context
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Overview of “Process”Overview of “Process”
IDENTIFICATION
setuid(2)setgid(2)
SET USER AND GROUP IDS
getuid(2)geteuid(2)getgid(2)getegid(2)
Get real user, effective user, real group, and effective group IDs
getgroups(2)setgroups(2)
Get or set supplementary group access list IDs
Relationships
getpid(2)getpgrp(2)getppid(2)getpgid(2)
Get process, process group, and parent process IDs
setpgrp(2) Set process group ID
setpgid(2) Set process group ID
setsid(2) Set session ID
File System
chdir(2)fchdir(2)
Change working directory
chroot(2) Change root directory
Runtime Linking
dlclose(3DL) Close a shared object
dlerror(3DL) Get diagnostic information
dlopen(3DL) Open a shared object
dlsym(3DL) Get the address of a symbol in a shared object
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Create a processCreate a process fork, vfork & system: textbook, p162fork, vfork & system: textbook, p162
Notes: Notes:
1. Two generic use for fork: fork & no exec, fork + exec (spawn)1. Two generic use for fork: fork & no exec, fork + exec (spawn)
2. The two main reasons for fork to fail: 2. The two main reasons for fork to fail:
3. Why the child’s PID is returned to the parent process, and a 3. Why the child’s PID is returned to the parent process, and a zero to the child? zero to the child?
4. The child process is a replica of the parent. 4. The child process is a replica of the parent.
5. Copy-on-write(COW) 5. Copy-on-write(COW)
6. The interaction of fork with the I/O functions: stdio functions 6. The interaction of fork with the I/O functions: stdio functions
7. File Sharing 7. File Sharing
8. Inherited properties from the parent process 8. Inherited properties from the parent process
9. Properties Different from the parent process9. Properties Different from the parent process
10. Fork() Safety in the multithreaded environment10. Fork() Safety in the multithreaded environment
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Running a programRunning a program
Notes:Notes:
In execlp/execvp, when a filename argument is specified, In execlp/execvp, when a filename argument is specified,
If filename contains a slash, it is taken as a If filename contains a slash, it is taken as a pathname pathname
For execl, execle, and execlp:For execl, execle, and execlp:
char *arg0, char *arg1, …, char *argn, char *arg0, char *arg1, …, char *argn, (char *)(char *)00
the total size of the argument list and the environment : the total size of the argument list and the environment : sysconf( ARG_MAX )sysconf( ARG_MAX )
Use Environ
Try eachPATH prefix
build argvbuild argv
execlp
execvp
execl
execv
build argv
execle
execve
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
exec() in the kernelexec() in the kernel
kernel code/data/stack
Memory mapped region for shared libraries
runtime heap (via malloc)
program text (.text)
initialized data (.data)
uninitialized data (.bss)
stack
forbidden
0
%espprocess VM
brk
0xc0
physical memorysame
for each process
process-specific datastructures
(page tables,task and mm structs)
kernel VM
To run a new program p in the To run a new program p in the current process using exec():current process using exec():
free vm_area_struct’s and free vm_area_struct’s and page tables for old areas.page tables for old areas.
create new vm_area_struct’s create new vm_area_struct’s and page tables for new areas.and page tables for new areas.
stack, bss, data, text, stack, bss, data, text, shared libs.shared libs.
text and data backed by text and data backed by ELF executable object file.ELF executable object file.
bss and stack initialized to bss and stack initialized to zero.zero.
set PC to entry point in .textset PC to entry point in .text
The kernel will swap in code The kernel will swap in code and data pages as needed.and data pages as needed.
.data.text
p
demand-zero
demand-zero
libc.so
.data.text
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Running a programRunning a program
Semantic of the exec familySemantic of the exec family
File descriptors open in the calling process image: close-on-exec File descriptors open in the calling process image: close-on-exec
Directory streams open in the calling process imageDirectory streams open in the calling process image
Signals set to the default action (SIG_DFL) Signals set to the default action (SIG_DFL)
Signals set to be caught by the calling process image: SIG_DFLSignals set to be caught by the calling process image: SIG_DFL
Signals set to be ignored (SIG_IGN) by the calling process image Signals set to be ignored (SIG_IGN) by the calling process image
In a shell which does not support job control, run “In a shell which does not support job control, run “cc xxx &cc xxx &””
any functions previously registered by any functions previously registered by atexit()atexit()
If the set-user-ID mode bit of the new process imageIf the set-user-ID mode bit of the new process image
Any shared memory segments attached to the calling process Any shared memory segments attached to the calling process image image
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Terminate a process (1)Terminate a process (1)
Ways for a process to terminate: Ways for a process to terminate:
Normal termination & Abnormal terminationNormal termination & Abnormal termination
Notify its parent how it terminatedNotify its parent how it terminated
Exit status & termination statusExit status & termination status
signal SIGCHLD: SA_NOCLDWAIT set by signactionsignal SIGCHLD: SA_NOCLDWAIT set by signaction
““zombie”: zombie”:
What happened if the parent terminates before the child? What happened if the parent terminates before the child?
Explanations for exit(): atexit() and tmpfile()Explanations for exit(): atexit() and tmpfile()
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Terminate a process (2)Terminate a process (2)53 /* 54 * Exit, flushing stdio buffers if necessary. 55 */ 56 void 57 exit( status ) 58 int status; 59 { 60 register struct atexit *p; 61 register int n; 62 63 #ifdef _THREAD_SAFE 64 extern int _thread_autoinit_dummy_decl; 65 /* Ensure that the auto-initialization routine is linked in: */ 66 _thread_autoinit_dummy_decl = 1; 67 #endif 68 69 for (p = __atexit; p; p = p->next) 70 for (n = p->ind; --n >= 0;) 71 (*p->fns[n])(); 72 if (__cleanup) 73 (*__cleanup)(); 74 _exit(status); 75 }
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Terminate a process (3)Terminate a process (3) 49 void 50 abort() 51 { 52 sigset_t mask; 53 54 /* 55 * POSIX requires we flush stdio buffers on abort 56 */ 57 if ( __cleanup ) 58 (*__cleanup)(); 59 60 sigfillset( &mask ); 61 /* 62 * don't block SIGABRT to give any handler a chance; we ignore 63 * any errors -- X311J doesn't allow abort to return anyway. 64 */ 65 sigdelset( &mask, SIGABRT ); 66 #ifdef _THREAD_SAFE 67 _thread_sys_sigprocmask(SIG_SETMASK, &mask, (sigset_t *)NULL); 68 #else 69 (void)sigprocmask( SIG_SETMASK, &mask, (sigset_t *)NULL ); 70 #endif 71 (void)kill( getpid(), SIGABRT ); 72 73 exit( 1 ); 74 }
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Cleaning up terminated process (1)Cleaning up terminated process (1)Function Description Prototype
wait suspend execution of the calling suspend execution of the calling thread until status information for thread until status information for one of one of its terminated childits terminated child processes is available, or until processes is available, or until delivery of a signaldelivery of a signal whose action whose action is either to execute a signal-is either to execute a signal-catching function or to terminate catching function or to terminate the process the process
pid_t wait( int * stat );
waitpid pid_t waitpid( pid_t pid, int * stat, int options );
waitid (x) suspends the calling process until suspends the calling process until one of its child processes one of its child processes changes changes statestate. It records the current state . It records the current state of a child in the structure pointed of a child in the structure pointed to by infop. to by infop.
int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options);
wait3 Wait3() and wait4() allow the Wait3() and wait4() allow the kernel to return a summary kernel to return a summary of the resources used by the of the resources used by the terminated process and all terminated process and all its child processes.its child processes.
pid_t wait3(int *status, int pid_t wait3(int *status, int options, struct rusage options, struct rusage *rusage);*rusage);
wait4 pid_t wait4(pid_t pid, int pid_t wait4(pid_t pid, int *status, int options, struct *status, int options, struct rusage *rusage);rusage *rusage);
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Cleaning up terminated process (2)Cleaning up terminated process (2)Constant Description
WNOHANG
WUNTRACED Job control, stopped child processes
Pid’s value
Pid == -1
Pid > 0
Pid == 0
Pid < -1
Macro
WIFEXITED( status ) WEXITSTATUS( status )
WIFSIGNALED( status ) WTERMSIG( status )
WIFSTOPPED( status ) WSTOPSIG( status )
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Cleaning up terminated process (3)Cleaning up terminated process (3)
#define WIFEXITED(stat) ((int)((stat)&0xFF) == 0)#define WIFSIGNALED(stat) ((int)((stat)&0xFF) > 0 && \ (int)((stat)&0xFF00) == 0)#define WIFSTOPPED(stat) ((int)((stat)&0xFF) == 0177 && \ (int)((stat)&0xFF00) != 0)
#define WEXITSTATUS(stat) ((int)(((stat)>>8)&0xFF))#define WTERMSIG(stat) ((int)((stat)&0x7F))#define WSTOPSIG(stat) ((int)(((stat)>>8)&0xFF))
The waitpid() function provides three features that are not The waitpid() function provides three features that are not provided by the wait function: provided by the wait function:
waitpid() lets us wait for one particular process (whereas wait() waitpid() lets us wait for one particular process (whereas wait() returns the status of any terminated child). returns the status of any terminated child).
waitpid() provides a nonblocking version of wait(). There are waitpid() provides a nonblocking version of wait(). There are times where we want to fetch a child’s status, but we don’t want times where we want to fetch a child’s status, but we don’t want to block. For example, receiving the signal SIGCHLD. to block. For example, receiving the signal SIGCHLD.
waitpid() supports job control(with the WUNTRACED option). waitpid() supports job control(with the WUNTRACED option).
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Cleaning up terminated process (4)Cleaning up terminated process (4)/* the init process */handle( sig_t handler, ... ){ int sig; struct sigaction sa; sigset_t mask_everything; va_list ap;
va_start( ap, handler );
sa.sa_handler = handler; sigfillset( &mask_everything );
while ( ( sig = va_arg(ap, int ) ) != NULL ) { sa.sa_mask = mask_everything; /* XXX SA_RESTART? */ sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0; sigaction( sig, &sa, (struct sigaction *) 0 ); }
va_end( ap );}
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Signal OverviewSignal Overview
Unix are designed around a Unix are designed around a virtual-machine modelvirtual-machine model, in , in which system calls are considered to be the parallel of which system calls are considered to be the parallel of machines’ hardware instruction set. machines’ hardware instruction set. Signals are the Signals are the software equivalent of traps or interruptsoftware equivalent of traps or interrupt, a signal-, a signal-handling routine perform the equivalent function of handling routine perform the equivalent function of interrupt or trap service routines. interrupt or trap service routines.
How does the hardware interrupt work? How does the hardware interrupt work?
Interruption source -> 8259 controller->cpu->interrupt vector Interruption source -> 8259 controller->cpu->interrupt vector table->interrupt service routinestable->interrupt service routines
How to write a interrupt handler? How to write a interrupt handler?
Save the context, set the interrupt maskSave the context, set the interrupt mask
May change another stackMay change another stack
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Signal OverviewSignal Overview
=> signal generation, => signal generation,
The kernel is the interrupt controller, The kernel is the interrupt controller,
The destination process is the CPU: mask register, handler vector, etcThe destination process is the CPU: mask register, handler vector, etc
Hardware machine Software virtual machine
Instruction set Set of system calls
Restartable instructions Restartable system calls
Interrupts/traps Signals
Interrupt/trap handlers Signal handlers
Blocking interrupts Masking signals
Interrupt stack Signal stack
DMA Operations Asynchronous I/O operations
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Signal OverviewSignal Overview
Signal GenerationSignal Generation
ExceptionsExceptions
Other processes: sigsend()Other processes: sigsend()
Terminal interrupts: CTRL+cTerminal interrupts: CTRL+c
Job control: stop and continue, notify their parent processJob control: stop and continue, notify their parent process
QuotasQuotas
Notifications: aioNotifications: aio
Alarms: setitimer(), generated by the callout threadAlarms: setitimer(), generated by the callout thread
Actions for signalActions for signal
Default, IGN, Specific HandlerDefault, IGN, Specific Handler
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Signal overviewSignal overview
How does the kernel send a signal to the destination How does the kernel send a signal to the destination process?process?
1. get the signal number and the process control block1. get the signal number and the process control block
2. check PCB’s signal block mask, and ignored mask2. check PCB’s signal block mask, and ignored mask
3. if PCB blocked this signal, then pending3. if PCB blocked this signal, then pending
4. if PCB ignored this signal, then discarded now. 4. if PCB ignored this signal, then discarded now.
*** in Solaris, semantics of SIGCHLD*** in Solaris, semantics of SIGCHLD
5. if PCB has a signal hander installed for this signal 5. if PCB has a signal hander installed for this signal
What is the destination process doing now? What is the destination process doing now?
If sleeping for a system call, then wakeup it now. If sleeping for a system call, then wakeup it now.
Put the signal into the process’ signal-q. Put the signal into the process’ signal-q.
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Signal overviewSignal overview
Signal handling: Signal handling:
only be taken by the receiving process itself, so only be taken by the receiving process itself, so the process must the process must be scheduled to run. be scheduled to run.
The receiving process becomes aware of the signal when the The receiving process becomes aware of the signal when the kernel does check for pending signal. The kernel checks at the kernel does check for pending signal. The kernel checks at the following times: following times:
Before returning to user mode Before returning to user mode from a system call or interruptfrom a system call or interrupt. .
Just before blocking on an interruptible event. Just before blocking on an interruptible event.
Immediately after waking up from an interruptible event.Immediately after waking up from an interruptible event.
How does the kernel prepare the context for the signal handler? How does the kernel prepare the context for the signal handler?
Stack frame: signum, siginfo_t, ucontext *, and a instruction Stack frame: signum, siginfo_t, ucontext *, and a instruction which will re-enter the kernel againwhich will re-enter the kernel again
Nested signal handling??? Very Difficult. Nested signal handling??? Very Difficult.
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Signal overviewSignal overview
Conclusions:Conclusions:
Signals generated by asynchronous events may occur after Signals generated by asynchronous events may occur after any any instructioninstruction in the code path of the process. in the code path of the process.
We need mechanisms to block the specific signals during We need mechanisms to block the specific signals during running. The most progress in O.S. designrunning. The most progress in O.S. design
Book, p6-7Book, p6-7
In multithreaded program, signal handling becomes rather In multithreaded program, signal handling becomes rather difficult there. difficult there.
In Solaris’s implementation, signal handling is difficult too. In Solaris’s implementation, signal handling is difficult too.
Generation -> notification -> redirect -> delivered Generation -> notification -> redirect -> delivered
There is a LWP to wait for signals, and then dispatch to a There is a LWP to wait for signals, and then dispatch to a thread. thread.
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Signal Handling in LinuxSignal Handling in Linux
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
History about signal handlingHistory about signal handling unreliable signal: See two classical code: race conditionunreliable signal: See two classical code: race condition
example 1: int sig_int(); /* singal hander */ int main( int argc, char **argv ){ ... signal( SIGINT, sig_int ); /* install my own signal handler */ ....}
voidsig_int( int signum ){ /* here the kernel sends a signal again, I don’t get it here.. */
signal( SIGINT, sig_int ); /* reinstall the signal handler */ }
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
History about signal handlingHistory about signal handlingExample 2:static volatile sig_atomic_t sig_int_flag; /* set nonzero when signal occurs */
intmain( int argc, char **argv ){ int sig_int(); signal( SIGINT, sig_int ); while ( sig_int_flag == 0 ) /* I may lose the signal here */ pause(); /* waiting for a incoming signal */ ...}
void sig_int( int signum ){ signal( SIGINT, sig_int ); sig_int_flag = 1;}
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
History about signal handlingHistory about signal handling
Reliable signal handlingReliable signal handling
1. permanent signal handling1. permanent signal handling
2. masking to protect the critical area: masked = blocked2. masking to protect the critical area: masked = blocked
3. atomic unblocked and waiting operation: sigsuspend()3. atomic unblocked and waiting operation: sigsuspend()
4. for performance, put signal masks into PCB, so we need not 4. for performance, put signal masks into PCB, so we need not wakeup some process nowwakeup some process now
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Issues about signal handlingIssues about signal handling
Restartable system callsRestartable system calls
Waiting for a device operation of slow speed: socket, terminalWaiting for a device operation of slow speed: socket, terminal
errno == EINTRerrno == EINTR
Reentrant functionsReentrant functions
Called by both the main program and signal handlerCalled by both the main program and signal handler
stdio, malloc/free, routines using global variablesstdio, malloc/free, routines using global variables
I/O operations with timeoutI/O operations with timeout
Use longjmp() & setjmp(), but Use longjmp() & setjmp(), but signal interactionsignal interaction
Use select()/poll()Use select()/poll()
There is no other good means for this requirements now.There is no other good means for this requirements now.
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Functions about signal (1)Functions about signal (1)
1. sending signals1. sending signals
kill( pid_t pid, int sig ): pid, see waitpid()kill( pid_t pid, int sig ): pid, see waitpid()
sigsend( idtype_t, id_t, int ): idtype_t, see waitid()sigsend( idtype_t, id_t, int ): idtype_t, see waitid()
2. using signal sets2. using signal sets
sigset_t: p6-11sigset_t: p6-11
sigprocmask(): p6-12, 13, operating the process’ blocked masksigprocmask(): p6-12, 13, operating the process’ blocked mask
Remember: restore the old mask: SIG_SETMASKRemember: restore the old mask: SIG_SETMASK
Catching signals: p6-15, 16, 17, 18, Catching signals: p6-15, 16, 17, 18,
void ( *signal( int signum, void (*sighandler)(int) ) )(int);void ( *signal( int signum, void (*sighandler)(int) ) )(int);
Using sigaction() is the best choice. Using sigaction() is the best choice.
Flag SA_SIGINFOFlag SA_SIGINFO
See the examples sigaction.c: use workshop to evaluate siginfo_t See the examples sigaction.c: use workshop to evaluate siginfo_t
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Functions about signal (2)Functions about signal (2)
Catching SIGCHLDCatching SIGCHLD
1. in the main program, invoke wait()/waitpid()1. in the main program, invoke wait()/waitpid()
2. install a SIGCHLD handler, and in which we should use wait2. install a SIGCHLD handler, and in which we should use wait
3. ignore SIGCHLD3. ignore SIGCHLD
4. use sigaction() and the flag SA_NOCLDWAIT4. use sigaction() and the flag SA_NOCLDWAIT
5. fork() and fork(): ask the init process reap my sons5. fork() and fork(): ask the init process reap my sons
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Example - SIGCHLDExample - SIGCHLD1.1. void childhandler( int signo ) void childhandler( int signo )
2.2. {{
… …
3.3. saveerrno = errno;saveerrno = errno;
4.4. /* get all outstanding terminated children *//* get all outstanding terminated children */
5.5. for ( ;; ) for ( ;; )
6.6. { {
7.7. pid = waitpid( -1, &status, WNOHANG );pid = waitpid( -1, &status, WNOHANG );
8.8. if ( pid == 0 ) {if ( pid == 0 ) {
9.9. /* 1. no dead children, but some live ones *//* 1. no dead children, but some live ones */
10.10. break;break;
11.11. } else if ( pid == -1 && errno == ECHILD ) {} else if ( pid == -1 && errno == ECHILD ) {
12.12. /* 2. no more children, dead or running *//* 2. no more children, dead or running */
13.13. break;break;
14.14. } else if (pid == -1) {} else if (pid == -1) {
15.15. /* should not get this *//* should not get this */
16.16. perror("waitpid");perror("waitpid");
17.17. abort();abort();
18.18. }}
19.19. /* 3. status contains the reaped status of one child *//* 3. status contains the reaped status of one child */
20.20. /* If desired, save status for main program. *//* If desired, save status for main program. */
21.21. }}
22.22. errno = saveerrno;errno = saveerrno;
23.23. return;return;
24.24. }} // // sig_atomic_t sig_atomic_t
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Functions about signal (3)Functions about signal (3)
Using alarm signalsUsing alarm signals
alarm(), Textbook, p167: timeout.calarm(), Textbook, p167: timeout.c
setitimer() & getitimer():setitimer() & getitimer():
setitimer(): itimerval.it-value, current value?setitimer(): itimerval.it-value, current value?
!!!! Read man setitimer carefully, specially used in the !!!! Read man setitimer carefully, specially used in the multithreaded environmentmultithreaded environment
Notes: Notes:
Timer set by setitimer() is permanent. Timer set by setitimer() is permanent.
There is only 4 timers for one process. So we need implement our own There is only 4 timers for one process. So we need implement our own software timeout mechanism sometime. software timeout mechanism sometime.
Hint: Data-link timer queue management Hint: Data-link timer queue management
sigsetjmp() & siglongjmp() & timeout => timed system callsigsetjmp() & siglongjmp() & timeout => timed system call
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Functions about signal (4)Functions about signal (4)
Waiting for a signal:Waiting for a signal:
sigpause( int signum ); a particular signalsigpause( int signum ); a particular signal
Used in the synchronization between parent & child processesUsed in the synchronization between parent & child processes
sigsuspend( sigset_t *set ); /****** important *******/sigsuspend( sigset_t *set ); /****** important *******/
Atomic unblock and waiting: reliable signalAtomic unblock and waiting: reliable signal
Example: Example:
sigprocmask( SIG_BLOCK, &newset, &oldmask );sigprocmask( SIG_BLOCK, &newset, &oldmask );
/* critical region *//* critical region */
if ( condition ) /* may while ( flag ), */if ( condition ) /* may while ( flag ), */
sigsuspend( &set );sigsuspend( &set );
sigprocmask( SIG_SETMASK, &oldmask, NULL );sigprocmask( SIG_SETMASK, &oldmask, NULL );
Remember: during waiting for a signal, and at the Remember: during waiting for a signal, and at the same time invoking a system call, same time invoking a system call, no reliable waysno reliable ways now.now.
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
ExerciseExercise
1. Notes: 1. Notes:
The child process's tms structure is cleared: tms_utime , stime , The child process's tms structure is cleared: tms_utime , stime , cutime , and cstime are set to 0 (using cutime , and cstime are set to 0 (using times(2)times(2)).).
The child processes resource utilizations are set to 0. The The child processes resource utilizations are set to 0. The it_value and it_interval values for the ITIMER_REAL timer are it_value and it_interval values for the ITIMER_REAL timer are reset to 0.reset to 0.
The set of signals pending for the child process is initialized to The set of signals pending for the child process is initialized to the empty set.the empty set.
Suggestions:Suggestions:
Take into more and more careful consideration: interactions Take into more and more careful consideration: interactions
Use the traditional ways to handle signalUse the traditional ways to handle signal
Separate the signal handling/critical region from the remainderSeparate the signal handling/critical region from the remainder
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Process Relationship (1)Process Relationship (1)
Controlling Terminal
Process Group
Current
Session
foreground
Background
Process
Parent1
1..n
+BelongTo
1
1..n
Leader
UserGroup
User
euid
11
Supplementary
ruid
saved_euid
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
Process Relationship (3)Process Relationship (3)
Session
Background Process GroupSession Leader = Controlling
Process Background Process Group
Foreground Process Group
ControllingTerminal
Han
gup
Sig
nal
Terminal In
put and terminal-generated signals
History: System V & BSD => Session( job control, login )History: System V & BSD => Session( job control, login )
The init processThe init process
Unix Programming Environment Unix Programming Environment Dept. of CSE, BUAADept. of CSE, BUAA
System and Process InformationSystem and Process Information
Host information: Book, p3-4,Host information: Book, p3-4,
System variablesSystem variables
File and directory limitsFile and directory limits
Machine timeMachine time
Converting timeConverting time
Time usage Time usage