Post on 16-Aug-2020
Li /UNIX P iLi /UNIX P iLinux/UNIX ProgrammingLinux/UNIX Programming
APUE (Process Control)APUE (Process Control)
문양세문양세양세양세강원대학교강원대학교 ITIT대학대학 컴퓨터과학전공컴퓨터과학전공
강의강의 내용내용APUE (Process Control)
프로세스 ID
프로세스 생성프로세스 생성
프로세스 종료
레이스 컨디션
프로그램 실행프로그램 실행
기타
UNIX System Programmingby Yang-Sae MoonPage 2
Process Identifiers (1/2)Process Identifiers (1/2)APUE (Process Control)
Every process has a unique process ID, a nonnegative integer.(모든 프로세스는 양수의 유일한 식별자(PID)를 가짐)(모든 프로세스는 양수의 유일한 식별자(PID)를 가짐)
Process ID 0: swapper
• scheduler process (it controls time slots for processes)
• system process
• part of the kernel
• no program on disk corresponds to this process
UNIX System Programmingby Yang-Sae MoonPage 3
Process Identifiers (2/2)Process Identifiers (2/2)APUE (Process Control)
Process ID 1: init process
invoked by the kernel at the end of the bootstrap procedure• invoked by the kernel at the end of the bootstrap procedure
• /etc/init or /sbin/init
d h d d l f l• reads the system-dependent initialization files (/etc/rc*)
• brings the system to a certain state (multi-user)
• a normal user process but runs with super-user privileges
• PID 1 is immortal
Process ID 2: pagedaemon
• supports the paging of the virtual memory system
• kernel process
UNIX System Programmingby Yang-Sae MoonPage 4
p
System Process System Process 예제예제APUE (Process Control)
UNIX System Programmingby Yang-Sae MoonPage 5
PID PID 관련관련 함수함수APUE (Process Control)
#include <sys/types.h>#include <unistd.h>
pid_t getpid(void); // returns process IDpid_t getppid(void); // returns parent process IDuid t getuid(void); // returns real user ID_ g ( ); //uid_t geteuid(void); // returns effective user IDgid_t getgid(void); // returns real group IDgid_t getegid(void); // returns effective group ID
None of these functions has an error return.
UNIX System Programmingby Yang-Sae MoonPage 6
강의강의 내용내용APUE (Process Control)
프로세스 ID
프로세스 생성프로세스 생성
프로세스 종료
레이스 컨디션
프로그램 실행프로그램 실행
기타
UNIX System Programmingby Yang-Sae MoonPage 7
fork() (1/3)fork() (1/3)APUE (Process Control)
#include <sys/types.h>#include <unistd.h>
( )pid_t fork(void);
fork() is the ONLY way to create a process in Unix kernelfork() is the ONLY way to create a process in Unix kernel.
Child process is the new process created by fork().
fork() is called once, but returns twice!
• returns 0 in child process.
• returns the child process ID in parent process.
UNIX System Programmingby Yang-Sae MoonPage 8
fork() (2/3)fork() (2/3)APUE (Process Control)
Child gets a copy of parent’s data space, heap, and stack
Often read only text segment is shared• Often, read-only text segment is shared
Parent and child continue executing instructionsfollowing the fork() call
Often, fork() is followed by exec().Often, fork() is followed by exec().
UNIX System Programmingby Yang-Sae MoonPage 9
fork() (3/3)fork() (3/3)APUE (Process Control)
main()
BEFORE fork() pid: 12791main() {...rtn = fork();...}
TEXT
}DATASTACK
USER AREAUSER AREA
i () i ()
AFTER fork()pid: 12791 pid: 12793
main() {...rtn = fork();...
TEXTmain() {...rtn = fork();...
TEXT
}DATASTACK
USER AREA
}DATASTACK
USER AREA
UNIX System Programmingby Yang-Sae MoonPage 10
USER AREA USER AREA
예제예제: fork.c (1/2): fork.c (1/2)APUE (Process Control)
UNIX System Programmingby Yang-Sae MoonPage 11
예제예제: fork.c (2/2): fork.c (2/2)APUE (Process Control)
실행 결과
UNIX System Programmingby Yang-Sae MoonPage 12
File Sharing after fork()File Sharing after fork()APUE (Process Control)
Parent and child share the same file descriptors.Parent and child share the same file offset.Therefore, intermixed output will occur from parent and child.
parent process table entry file table
v-node tablev-nodeentry
file descriptorsfd 0:fd 1:
fd flags ptr
file tablefd status flagscurrent file offsetv-node ptr
v nodeinformation
i-nodeinformation
fd 2:. . . . fd status flags
current file offsetv-node ptr
current file size
v-nodeinformation
file descriptorsfd 0: fd flags ptr
child process table entry fd status flags
current file offsetv-node ptr
informationi-node
information
current file sizefd 0:fd 1:fd 2:
. . . .
fd flags ptr v node ptr
v-nodeinformation
i-node
UNIX System Programmingby Yang-Sae MoonPage 13
i-nodeinformation
current file size
Properties Inherited to the ChildProperties Inherited to the ChildAPUE (Process Control)
real user and group ID, effective user and group ID
supplementary group IDssupplementary group IDs
process group ID, session ID
set user ID and set group ID flagsset-user-ID and set-group ID flags
current working directory
t di troot directory
file mode creation mask
signal mask and dispositions
the close-on-exec flag for any open file descriptors
environment
attached shared memory segments
UNIX System Programmingby Yang-Sae MoonPage 14
resource limits
Properties NOT Inherited to the ChildProperties NOT Inherited to the ChildAPUE (Process Control)
the return value from fork()
the process IDs are differentthe process IDs are different
file locks
pending alarms are cleared for the childpending alarms are cleared for the child
the set of pending signals for the child is set to the empty set
UNIX System Programmingby Yang-Sae MoonPage 15
강의강의 내용내용APUE (Process Control)
프로세스 ID
프로세스 생성프로세스 생성
프로세스 종료
레이스 컨디션
프로그램 실행프로그램 실행
기타
UNIX System Programmingby Yang-Sae MoonPage 16
exit() exit() –– Process TerminationProcess TerminationAPUE (Process Control)
A process can terminate in 5 ways:
Normal Termination
• return from main()
• exit() w/ cleanup procedure() p p
• _exit() w/o cleanup procedure
Abnormal Termination
• calling abort() (generates SIGABRT signal)
• process receives signals
UNIX System Programmingby Yang-Sae MoonPage 17
exit() exit() –– Termination Termination StatusStatus –– skip skip APUE (Process Control)
Exit Status:
argument of exit() exit() • argument of exit(), _exit()
• the return value from main()
Termination Status:
• Normal termination: Exit status Termination status
• Abnormal termination: kernel indicates reason Termination status
Parent can obtain the termination status of the child process.p
• by wait() or waitpid()
Wh t if t t i t b f hild?What if parent terminates before child?
• init(PID = 1) becomes the parent of the child process
UNIX System Programmingby Yang-Sae MoonPage 18
exit() exit() –– Child Child TerminationTermination –– skip skip APUE (Process Control)
Suppose child terminates first
If child disappeared parent would not be able to check child’s termination status• If child disappeared, parent would not be able to check child’s termination status.
• Zombie: minimal info of dead child process (pid, termination status, CPU time) kept by the kernel for the parent to call wait() or waitpid()by the kernel for the parent to call wait() or waitpid()
Zombie가 되지 않도록 하기 위해서는 Parent가 wait()해 주어야 함
UNIX System Programmingby Yang-Sae MoonPage 19
wait(), wait(), waitpidwaitpid() (1/2() (1/2)) –– skip skip APUE (Process Control)
Child terminates
Kernel sends SIGCHLD signal to parent• Kernel sends SIGCHLD signal to parent.
• an asynchronous event
Default action for signal: ignore it.
Signal handlers can be defined by usersg y
• call wait() to fetch the termination status of child.
• (무사히 죽을 수 있도록 배려~)• (무사히, 죽을 수 있도록 배려~)
UNIX System Programmingby Yang-Sae MoonPage 20
wait(), wait(), waitpidwaitpid() (2/2() (2/2)) –– skip skip APUE (Process Control)
#include <sys/types.h>#include <sys/wait.h>
pid_t wait(int *statloc);pid_t waitpid(pid_t pid, int *statloc, int options);
Both returns: process ID if OK, 0, or -1 on error
A process that calls wait or waitpid can
ot etu s: p ocess O , 0, o o e o
• block (if all of its children are still running), or
• return immediately with the termination status of a child, ory
• return immediately with an error (if it doesn’t have any child processes)
statlocstatloc
• a pointer to an integer to store the termination status
UNIX System Programmingby Yang-Sae MoonPage 21
options: refer to manual of waitpid()
Macros to examine the termination Macros to examine the termination statusstatus –– skip skip APUE (Process Control)
Macro Description
WIFEXITED(status)True if child is terminated normallyWEXITSATUS(status) : get exit status (low-order 8 bits)
WIFSIGNALED(status)True if child is terminated abnormally (by receipt of a signal)WTERMSIG(status): fetch the signal number that caused the termination.
T if hild i tl t dWIFSTOPPED(status)
True if child is currently stoppedWSTOPSIG(status): fetch the signal number that caused the stop.
UNIX System Programmingby Yang-Sae MoonPage 22
예제예제: : nwait.cnwait.c (1/3(1/3)) –– skip skip APUE (Process Control)
#include <stdio.h> // nwait.c#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>
void pr_exit(int status) {if (WIFEXITED(status))printf("normal termination, exit status = %d\n“, WEXITSTATUS(status));
else if (WIFSIGNALED(status))else if (WIFSIGNALED(status))printf("abnormal termination, signal number = %d\n", WTERMSIG(status));
else if (WIFSTOPPED(status))printf("child stopped, signal number = %d\n", WSTOPSIG(status));
}
UNIX System Programmingby Yang-Sae MoonPage 23
예제예제: : nwait.cnwait.c (2/3(2/3)) –– skip skip APUE (Process Control)
int main(void) {pid_t pid;int status;
if((pid = fork()) < 0) err_sys("fork error");else if (pid == 0) exit(7); /* child */
if(wait(&status) != pid) err sys("wait error"); /* wait for child */p _ ypr_exit(status);
if((pid = fork()) < 0) err_sys("fork error");else if (pid == 0) /* child */abort(); /* generates SIGABRT */abort(); /* generates SIGABRT */
if(wait(&status) != pid) err_sys("wait error"); /* wait for child */pr_exit(status);
if((pid = fork()) < 0) err_sys("fork error");else if (pid == 0) /* child */status /= 0; /* divide by 0 generates SIGFPE */
if(wait(&status) != pid) err_sys("wait error"); /* wait for child */pr_exit(status);
exit(0);
UNIX System Programmingby Yang-Sae MoonPage 24
( );}
예제예제: : nwait.cnwait.c (3/3(3/3)) –– skip skip APUE (Process Control)
실행 결과
UNIX System Programmingby Yang-Sae MoonPage 25
강의강의 내용내용APUE (Process Control)
프로세스 ID
프로세스 생성프로세스 생성
프로세스 종료 (전체 생략)
레이스 컨디션
프로그램 실행프로그램 실행
기타
UNIX System Programmingby Yang-Sae MoonPage 26
Race Conditions (1/2)Race Conditions (1/2)APUE (Process Control)
Multiple processes share some data.
Outcome depends on the order of their execution (i e RACE)Outcome depends on the order of their execution (i.e. RACE)
• (Process A) x = 20;
(Process B) x + 10;• (Process B) x += 10;
After fork(), we cannot predict if the parent or the child runs first!
The order of execution depends on:
• System Load
• Kernel’s Scheduling Algorithm
UNIX System Programmingby Yang-Sae MoonPage 27
Race Conditions (2/2)Race Conditions (2/2)APUE (Process Control)
For parent to wait for child,
• Call wait(), waitpid(), wait3(), wait4()Call wait(), waitpid(), wait3(), wait4()
• Use signals or other IPC methods
For child to wait for parentFor child to wait for parent,
• while(getppid() != 1) sleep(1); // Parent가 죽을 때까지 기다림
• Use signals or other IPC methods• Use signals or other IPC methods
UNIX System Programmingby Yang-Sae MoonPage 28
예제예제: race.c (1/2): race.c (1/2)APUE (Process Control)
#include <stdio.h> // race.c#include <sys/types.h>
err sys(char *p) { perror(p); exit( 1); }err_sys(char *p) { perror(p); exit(-1); }
int main(void) {pid_t pid;
if ((pid = fork()) < 0) err_sys("fork error");else if (pid == 0) charatatime("output from child\n");else charatatime("output from parent\n");exit(0);exit(0);
}
charatatime(char *str){{
char *ptr;int c;
for (ptr = str; c = *ptr++; ) {for (ptr = str; c = *ptr++; ) {putc(c, stdout);fflush(stdout);usleep(1);
}
UNIX System Programmingby Yang-Sae MoonPage 29
}}
예제예제: race.c (2/2): race.c (2/2)APUE (Process Control)
실행 결과
UNIX System Programmingby Yang-Sae MoonPage 30
How to Avoid Race Condition?How to Avoid Race Condition?APUE (Process Control)
#include <stdio.h>#include <sys/types.h>
i t i ( id) {int main(void) {pid_t pid;
TELL_WAIT();
if ((pid = fork()) < 0) err_sys("fork error");else if (pid == 0) {WAIT_PARENT(); // parent goes firstcharatatime("output from child\n");
} l {} else {charatatime("output from parent\n");TELL_CHILD(pid);
}exit(0);exit(0);
}
How to implement TELL WAIT() WAIT PARENT() and TELL CHILD()?How to implement TELL_WAIT(), WAIT_PARENT(), and TELL_CHILD()?
• Use signals (강의노트 15)
• Use IPC methods (강의노트 16)
UNIX System Programmingby Yang-Sae MoonPage 31
Use IPC methods (강의노트 16)
강의강의 내용내용APUE (Process Control)
프로세스 ID
프로세스 생성프로세스 생성
프로세스 종료
레이스 컨디션
프로그램 실행프로그램 실행
기타
UNIX System Programmingby Yang-Sae MoonPage 32
Program Execution: exec() (1/2)Program Execution: exec() (1/2)APUE (Process Control)
When a process calls one of the exec() functions
• that process is completely replaced by the new program (새로운 프로그램으로 대체)p p y p y p g (새 운 램 대체)
(text, data, heap, and stack segments)
• and the new program starts at its main function
함수 exec()를 호출하여 완전히 다른 프로그램으로 실행된다.
UNIX System Programmingby Yang-Sae MoonPage 33
Program Execution: exec() (2/2)Program Execution: exec() (2/2)APUE (Process Control)
BEFORE exec()pid: 12791 pid: 12791
AFTER exec()
main() {...execl("newpgm", ...);
CODEmain() {
...CODE
p p/*newpgm*/
...}
DATASTACK
}DATASTACK
USER AREA USER AREA
UNIX System Programmingby Yang-Sae MoonPage 34
exec() Functionsexec() FunctionsAPUE (Process Control)
#include <unistd.h>
int execl(const char *pathname const char *arg0 (char *)0);int execl(const char pathname, const char arg0, … , (char )0);
int execv(const char *pathname, const char *argv[]);
int execle(const char *pathname, const char *arg0, …
/* (char*) 0, char *const envp[] */);( ) , p[] )
int execve(const char *pathname, const char *argv[],char *const envp[]);
int execlp(const char *filename, const char *arg0, … , (char *)0);
int execvp(const char *filename, const char *argv[]);
All six return: -1 on error, no return on success
exec? (p, l, v, e)exec? (p, l, v, e)
• p: filename (not pathname)
• l: takes a list of arguments (the last argument should be a null pointer)
• v: takes argv[] vector
• e: takes envp[] array i h ‘ ’ h i i bl f h lli i d
UNIX System Programmingby Yang-Sae MoonPage 35
without ‘e’, the environment variables of the calling process are copied
Properties inherited to the new programProperties inherited to the new programAPUE (Process Control)
same ID
• process ID, parent process ID, real user ID, real group ID, supplementary group IDs, p , p p , , g p , pp y g p ,process group ID, session ID
controlling terminal
time left until alarm clock
current working directoryg y
root directory
file mode creation maskfile mode creation mask
file locks
process signal mask
pending signals
UNIX System Programmingby Yang-Sae MoonPage 36
resource limits, …
예제예제: : nexec.cnexec.c, , echoall.cechoall.c ((1/4)1/4)APUE (Process Control)
UNIX System Programmingby Yang-Sae MoonPage 37
예제예제: : nexec.cnexec.c, , echoall.cechoall.c (2/4)(2/4)APUE (Process Control)
UNIX System Programmingby Yang-Sae MoonPage 38
예제예제: : nexec.cnexec.c, , echoall.cechoall.c (3/4)(3/4)APUE (Process Control)
UNIX System Programmingby Yang-Sae MoonPage 39
APUE (Process Control)예제예제: : nexec.cnexec.c, , echoall.cechoall.c (4/4)(4/4)
실행 결과
UNIX System Programmingby Yang-Sae MoonPage 40
강의강의 내용내용APUE (Process Control)
프로세스 ID
프로세스 생성프로세스 생성
프로세스 종료
레이스 컨디션
프로그램 실행프로그램 실행
기타
UNIX System Programmingby Yang-Sae MoonPage 41
system()system()APUE (Process Control)
#include <stdlib.h>
int system(const char *cmdstring);
주어진 스트링(cmdstring)을 Shell 상에서 수행시킨다.
• e.g.) system(“date > file”);
system() is implemented by calling fork, exec, and waitpid.
Return values:
• -1 with errno: fork or waitpid fails
• 127: exec fails
• Termination status of shell: all 3 functions succeed
UNIX System Programmingby Yang-Sae MoonPage 42
예제예제: : system.csystem.c (1/2)(1/2)APUE (Process Control)
#include <sys/types.h> // system.c#include <sys/wait.h>#include <errno.h>#include <unistd.h>int system(const char *cmdstring) /* version without signal handling */{
pid_t pid; int status;
if( d i )if(cmdstring == NULL)return(1); /* always a command processor with Unix */
if((pid = fork()) < 0) {status = 1; /* probably out of processes */status = -1; /* probably out of processes */
} else if (pid == 0) { /* child */execl("/bin/sh", "sh", "-c", cmdstring, (char *) 0);exit(127); /* execl error */_exit(127); / execl error /
} else { /* parent */while (waitpid(pid, &status, 0) < 0)if (errno != EINTR) {status = -1; /* error other than EINTR from waitpid() */break;
}}
UNIX System Programmingby Yang-Sae MoonPage 43
return(status);}
예제예제: : system.csystem.c (2/2)(2/2)APUE (Process Control)
UNIX System Programmingby Yang-Sae MoonPage 44
예제예제: myls.c (1/2): myls.c (1/2)APUE (Process Control)
#include <stdio.h> // myls.c
main(int ac char *av[])main(int ac, char *av[]){
int i;char cmdstr[1024];[ ];
strcpy(cmdstr, "/bin/ls ");
for(i=1;i < ac;i++) {strcat(cmdstr, av[i]);strcat(cmdstr, " ");
}fprintf(stdout, "cmdstr = \"%s\"\n", cmdstr);
t ( d t )system(cmdstr);
exit(0);}
UNIX System Programmingby Yang-Sae MoonPage 45
}
예제예제: myls.c (2/2): myls.c (2/2)APUE (Process Control)
실행 결과
UNIX System Programmingby Yang-Sae MoonPage 46
Process Process TimesTimes –– skip skip APUE (Process Control)
#include <sys/times.h>
clock_t times(struct tms *buf);Returns: elapsed wall clock time in clock ticks if OK 1 on errorReturns: elapsed wall clock time in clock ticks if OK, -1 on error
struct tms (clock_t tms_utime; /* user cpu time */clock t tms stime; /* system cpu time */clock_t tms_stime; /* system cpu time */clock_t tms_cutime; /* child user cpu time */clock_t tms_cstime; /* child system cpu time */
}
Wall clock time: the amount of time the process takes to run and depends on the system loads. (실제 수행된 시간)p y
User CPU time: attributed to user instructions(사용자 코드에 의해 CPU를 점유한 시간)
System CPU time: attributed to the kernel, when it executes on behalf of the process (시스템 코드에 의해 CPU를 점유한 시간)
UNIX System Programmingby Yang-Sae MoonPage 47
예제예제: : times.ctimes.c (1/3(1/3) ) –– skip skip APUE (Process Control)
#include <stdio.h> // times.c#include <unistd.h>#include <sys/times.h>
err_sys(char *p) { perror(p); exit(-1); }
int main(int argc, char *argv[]) {int i;for (i = 1; i < argc; i++)for (i = 1; i < argc; i++)do_cmd(argv[i]); /* once for each command-line arg */
exit(0);}
do_cmd(char *cmd) /* execute and time the "cmd" */{
int status;clock_t start, end;struct tms tmsstart tmsend;struct tms tmsstart, tmsend;
fprintf(stderr, "\ncommand: %s\n", cmd);if ( (start = times(&tmsstart)) == -1) /* starting values */err sys("times error");_ y ( );
if ( (status = system(cmd)) < 0) /* execute command */err_sys("system() error");
if ( (end = times(&tmsend)) == -1) /* ending values */err_sys("times error");ti ( d t t &t t t &t d)
UNIX System Programmingby Yang-Sae MoonPage 48
pr_times(end-start, &tmsstart, &tmsend);}
예제예제: : times.ctimes.c (2/3(2/3) ) –– skip skip APUE (Process Control)
pr_times(clock_t real, struct tms *tmsstart, struct tms *tmsend){
static long clktck = 0;
if(clktck == 0) clktck = sysconf(_SC_CLK_TCK);
\ /fprintf(stderr, " real: %7.2f\n", real / (double) clktck);fprintf(stderr, " user: %7.2f\n",
(tmsend->tms_utime - tmsstart->tms_utime) / (double) clktck);fprintf(stderr, " sys: %7.2f\n",
/(tmsend->tms_stime - tmsstart->tms_stime) / (double) clktck);fprintf(stderr, " child user: %7.2f\n",
(tmsend->tms_cutime - tmsstart->tms_cutime) / (double) clktck);fprintf(stderr, " child sys: %7.2f\n",
( d i i ) / (d bl ) lk k)(tmsend->tms_cstime - tmsstart->tms_cstime) / (double) clktck);}
sysconf(_SC_CLK_TCK) ticks per second 값을 리턴함
UNIX System Programmingby Yang-Sae MoonPage 49
예제예제: : times.ctimes.c (3/3(3/3) ) –– skip skip APUE (Process Control)
실행 결과
UNIX System Programmingby Yang-Sae MoonPage 50