Presentation is loading. Please wait.

Presentation is loading. Please wait.

제11장 프로세스 시스템 프로그래밍 2011 가을 숙명여대 창병모.

Similar presentations


Presentation on theme: "제11장 프로세스 시스템 프로그래밍 2011 가을 숙명여대 창병모."— Presentation transcript:

1 제11장 프로세스 시스템 프로그래밍 2011 가을 숙명여대 창병모

2 목표 프로세스 시작/종료 자식 프로세스 생성 프로세스 내에서 새로운 프로그램 실행 시그널 시스템 부팅

3 프로세스 시작/종료

4 Process Start Kernel exec system call user process C start-up routine
return int main(int argc, char * argv[]);

5 main() int main(int argc, char *argv[]); C start-up routine
argc : the number of command-line arguments argv[] : an array of pointers to the arguments C start-up routine Started by the kernel (by the exec system call) Take the command-line arguments and the environment from the kernel Call main exit( main( argc, argv) );

6 Process Termination Normal termination Abnormal termination
return from main() calling exit() : calling _exit() Abnormal termination calling abort() terminated by a signal

7 exit() 프로세스를 정상적으로 종료한다 cleanup processing 을 수행한다 status
#include <stdlib.h> void exit(int status); 프로세스를 정상적으로 종료한다 cleanup processing 을 수행한다 모든 열려진 스트림을 닫고(fclose) 출력 버퍼의 내용을 디스크에 쓴다(fflush) status the exit status of a process 이 값은 UNIX shell 에 의해서 사용됨

8 _exit() 프로세스를 정상적으로 종료한다 커널로 즉시 리턴한다 #include <unistd.h>
void _exit(int status); 프로세스를 정상적으로 종료한다 커널로 즉시 리턴한다

9 Command-Line Arguments
exec() pass command-line arguments to a new program argv[0], argv[1], …, argv[argc-1] argv[argc] is NULL (ANSI, POSIX.1) argument list arguments argv argv[0] program 이름 argv[1] 1st argument argv[argc-1] (argc-1)th argument NULL

10 프로세스 구조

11 What is a process ? a process is
an executing program together with the program's data, stacks, user-area information about the program in kernel a process image is the layout of a process in memory a program is not a process by itself

12 Components of Process Code area Heap area Stack area User area
the executable code of a process Heap area static and global variables heap area Stack area runtime stack to hold activation records including local variables User area information like open fds, signal actions, etc

13 Process Image Code Stack Heap User-area

14 Kernel processes and user processes
process in user mode a system call make it into kernel mode Kernel process process in kernel mode the code is linked directly into the kernel

15 프로세스 생성

16 Creating a new process fork()
#include <sys/types.h> #include <unistd.h> pid_t fork(void); fork() is the ONLY way to create a process 자기복제 Child process is the new process created by fork() an almost-exact duplicate of the parent process code, data, stack, open file descriptors, etc.

17 fork() fork() is called once, but returns twice! Execution
returns 0 in child process returns the child process ID in parent process Execution Parent and child continue executing instructions following the fork() call Often, fork() is followed by exec()

18 Creating a new process BEFORE fork() pid: 12791 AFTER fork()
main() { ... rtn = fork(); } HEAP STACK USER AREA CODE BEFORE fork() AFTER fork() pid: 12791 pid: 12792

19 Process ID int getpid( ) Process ID int exit (int status)
return a process's id int getppid( ) return a parent process's id int exit (int status) a process terminates process by executing exit() frees its code, data, stack and closes a process's fds, sends its parent a SIGCHLD signal

20 wait( ) int wait(int* status)
wait() causes a process to suspend until one of its children terminate wait() returns the pid of the child that terminated and places a status code into *status

21 Example : fork and wait #include <stdio.h> main( ) { int pid, status, childPid; printf(“I’m the parent process and my PID is %d\n”, getpid( )); pid = fork( ); if (pid != 0) { printf(“I’m the parent process with PID %d and PPID %d\n”, getpid( ), getppid( )); childPid = wait(&status); printf(“A child with PID %d terminated with exit code %d\n” childPid, status>>8); } else { printf(“I’m the child process with PID %d and PPID %d\n”, exit(42); } printf(“PID %d terminates\n”, getpid() );

22 프로그램 실행

23 Program Execution: exec()
프로세스 내의 프로그램을 새 프로그램으로 대치 exec() 시스템 호출 사용 보통 fork() 후에 exec( ) When a process calls an exec function that process is completely replaced by the new program (text, data, heap, and stack segments) and the new program starts at its main function Successful exec never returns !

24 프로세스 내에서 새 프로그램 실행 ... execl(“newpgm”, …); HEAP STACK USER AREA CODE
main() // newpgm { } BEFORE exec( ) AFTER exec() pid: 12791

25 exec() Kernel exec system call user process C start-up routine call
return int main(int argc, char * argv[]);

26 exec Replace the calling process's code, data, and stack with the new program path , and execute the new program. Return a successful exec( ) never returns ! failure : -1 int execl(char* path, char* arg0, char* arg1, ... , char* argn, NULL) int execv(char* path, char* argv[ ])

27 Example : fork and exec Call exec( ) after calling fork( )
Create a new process and execute a program #include <stdio.h> main( ){ int fork( ); if (fork( ) == 0) { execl("/bin/echo", "echo", "this is message one", NULL); perror("exec one faild"); exit(1); } execl("/bin/echo", "echo", "this is message two", NULL); perror("exec two faild"); exit(2); execl("/bin/echo","echo", "this is message three",NULL); perror("exec three faild"); exit(3); printf("Parent program ending\n");

28 Example: Foreground Processing
Execute a program using fork( ) and exec( ) #include <stdio.h> main(int argc, char argv[]) { int child, pid; pid = fork( ); if (pid == 0) { execvp(argv[1], &argv[1]); fprintf(stderr, “Could not execute %s\n”,argv[1]); } else { child = wait(&status); printf(“A child with PID %d terminated with exit code %d\n”, pid, status>>8); }

29 기타 Changing directory Accessing user and group IDs
int chdir (char* pathname) set a process's current working directory to pathname the process must have execute permission for the directory returns 0 if successful; otherwise -1 Accessing user and group IDs int getuid() int setuid(int id) int getgid() int setgid(int id) returns the calling process's real user or group ids

30 Example #include <stdio.h> main( ) { system(“pwd”); chdir(“/”); chdir(“/user/faculty/chang”); }

31 Example: Redirection %redirect output command %redirect out ls –l
1) The parent forks and then waits for the child to terminate 2) The child opens the file "output“, and 3) Duplicates the fd of “output" to the standard output(fd=1), and close the fd of the original file 4) The child execute the “command”. All of the standard output of the command goes to "output“ 5) When the child shell terminates, the parent resumes %redirect out ls –l

32 Example: Redirection #include <stdio.h> main(argc, argv) int argc, argv[ ]; { int fd, status; if (fork() == 0) { fd=open(argv[1], O_CREAT|O_TRUNC|O_WRONLY, 0600) dup2(fd, 1); close(fd); execvp(argv[2], &argv[2]); perror(“main”); } else { wait(&status); printf(“Child is done\n”);

33 시스템 시작

34 시스템 시작 The First Process 0 sched 1 init 2 pagedaemon
the first process(sched) with pid =0 is created during boot time, and fork/exec twice. 0 sched 1 init 2 pagedaemon Process ID 0 : swapper (scheduler process) system process part of the kernel no program on disk corresponds to this process

35 시스템 시작 Process ID 1: init process Process ID 2: pagedaemon
invoked by the kernel( /etc/init or /sbin/init ) reads the system initialization files (/etc/rc*) brings the system to a certain state (multi-user) creates processes based upon script files getty, login process, mounting file systems, start daemon processes Process ID 2: pagedaemon supports the paging of the virtual memory system kernel process

36 Process hierarchy getty process(/etc/getty) login process
detects line activity and prompts with login exec /bin/login, after entering a response to the login prompt. login process checks a user's login and password against /etc/passwd exec /bin/sh or /bin/csh set the evnironment variables like HOME, LOGNAME, PATH... shell process execute commands in start-up files like /etc/.cshrc and ~/.cshrc shell starts its job

37 Process hierarchy sched(0) pagedaemon(2) init(1) … getty(10) httpd(5)
login(10) shell(10)

38 시그널(Signal)

39 Signals Process Signal #8
Signals are software interrupts from unexpected events a floating-point error a power failure an alarm clock the death of a child process a termination request from a user (Ctrl-C) a suspend request from a user (Ctrl-Z) Process Signal #8

40 Predefined signals 31 signals Every signal has a name
/usr/include/signal.h Every signal has a name begin with 'SIG' SIGABRT: abort signal from abort() SIGALRM: alarm signal from alarm() Actions of the default signal handler terminate the process and generate a core(dump) ignores and discards the signal(ignore) suspends the process (suspend) resume the process

41 Signal Generation Terminal-generated signals
CTRL-C  SIGINT CTRL-Z  SIGSTP signal Hardware exceptions generate signals divide by 0  SIGFPE invalid memory reference  SIGSEGV kill() sends any signal to a process or process group need to be owner or superuser Software conditions SIGALRM: alarm clock expires SIGPIPE: broken pipe SIGURG: out-of-band network data

42 Unix Signals SIGART SIGALRM SIGCHLD SIGCONT SIGFPE SIGHUP
generated by calling the abort function. SIGALRM generated when a timer set with the alarm expires. SIGCHLD Whenever a process terminates or stops, the signal is sent to the parent. SIGCONT This signal(job-control) sent to a stopped process when it is continued. SIGFPE signals an arithmetic exception, such as divide-by-0, floating point overflow, and so on SIGHUP disconnect detected, session leader terminates

43 Unix Signals SIGILL SIGINT SIGIO SIGKILL SIGPIPE
when the process has executed an illegal hardware instruction SIGINT generated by the terminal driver when we type the interrupt key and sent to all processes in the foreground process group SIGIO indicates an asynchronous I/O event SIGKILL can’t be caught or ignored. a sure way to kill any process. SIGPIPE If we write to a pipeline but the reader has terminated, SIGPIPE is generated

44 Unix Signals SIGSEGV SIGSTOP SIGSYS SIGTERM SIGTSTP
indicates that the process has made an invalid memory reference SIGSTOP This signal(job-control) stops a process and can’t be caught or ignored SIGSYS signals an invalid system call SIGTERM the termination signal sent by the kill(1) command by default. SIGTSTP Cntl-Z from the terminal driver which is sent to all processes in the foreground process group.

45 Handling of signals Action 3 kinds of actions
Process has to tell the kernel “if and when this signal occurs, do the following.” 3 kinds of actions Ignore the signal all signals can be ignored, except SIGKILL and SIGSTOP Catch the signal Call a function of ours when a signal occurs. The default action most are to terminate process

46 Example : Alarm.c #include <stdio.h> main( ) { alarm(3);
printf(“Looping forever …\n”); while (1) ; printf(“This line should never be executed\n”); } SIGALRM signal Default handler display message “Alarm clock”

47 Handling Signals: signal( )
Signal handler 등록 하나의 signal에 대한 hanlder 함수를 등록한다 signal(int sigCode, void (*func)( ))) specify the action for a signal sigCode func func SIG_IGN SIG_DFL user-defined function return the previous func

48 Handling Signals: Example
#include <stdio.h> #include <signal.h> int alarmFlag=0; alarmHandler( ); main( ) { signal(SIGALRM, alarmHandler); alarm(3); printf(“Looping …\n”); while(!alarmFlag) { pause( ); } printf(“Loop ends due to alarm signal \n”); } /* main */ alarmHandler( ) { printf(“An alarm clock signal was received\n”); alarmFlag = 1;

49 Example: Protecting Critical Code
#include <stdio.h> #include <signal.h> main ( ) { int (*oldHandler)( ); printf(“I can be Control-C’ed\n”); sleep(3); oldHandler = signal(SIGINT, SIG_IGN); printf(“I’m proctected from Control-C now\n”); signal(SIGINT, oldHandler); printf(“I can be Control-C’ed again\n”); }

50 Sending signals: kill()
int kill(int pid, int sigCode) send signal sigCode to the process pid condition for success the owner of the sending process = the owner of pid the owner of the sending process = super-user

51 Example: Time Limit #include <stdio.h> #include <signal.h> int delay; main(argc, argv) int argc; char *argv[ ]; { int pid; signal(SIGCHLD,childHandler); pid = fork(); if (pid == 0) { execvp(argv[2], &argv[2]); perror(“Limit”); } else { sscanf(argv[1], “%d”, &delay); sleep(delay); printf(“Child %d exceeded limit and is being killed\n”, pid); kill(pid, SIGINT); }

52 Example: Time Limit Usage
childHandler( ) /* Executed if the child dies before the parent */ { int childPid, childStatus; childPid = wait(&childStatus); printf(“Child %d terminated within %d seconds\n”, childPid, delay); exit(0); } Usage %limit 5 ls %limit 4 sleep 100

53 Example: Suspending and Resume
#include <signal.h> #include <stdio.h> main( ) { int pid1, pid2; pid1 = fork( ); if (pid1 == 0) { while(1) { printf(“pid1 isalive\n”); sleep(1); } } pid2 = fork( ); if (pid2 == 0) while (1) { printf(“pid2 is alive\n”); sleep(1); } sleep(3); kill(pid1, SIGSTOP); sleep(3); kill(pid1, SIGCONT); sleep(3); kill(pid1, SIGINT); kill(pid2, SIGINT);


Download ppt "제11장 프로세스 시스템 프로그래밍 2011 가을 숙명여대 창병모."

Similar presentations


Ads by Google