1.42k likes | 1.92k Views
Ch4 Linux System Programming – Process & IPC. Jianjian SONG Software Institute, Nanjing University Oct, 2004. Content. Process & process environment Process Control Process identifier, fork, exec … Process relationship Signal Inter-process communication (IPC) Pipe, FIFO
E N D
Ch4 Linux System Programming– Process & IPC Jianjian SONG Software Institute, Nanjing University Oct, 2004
Content • Process & process environment • Process Control • Process identifier, fork, exec… • Process relationship • Signal • Inter-process communication (IPC) • Pipe, FIFO • semaphore, shared memory, message queue • Daemon • Thread
1. Process & Process Environment • What is a process? • Program and process • Process: an address space with one or more threads executing within that address space, and the required system resources for those threads. (SUSv3)
The startup of a process • System call “fork” • Process resources • struct task_struct • System space stack • … • System call “exec” • The entry of C programs
The entry of C programs • crt0.o • cc/ld • main function • function prototype: int main(int argc, char *argv[]);
The termination of a process • Five ways of terminating a process • Normal termination • Return from “main” function • Call “exit” function • Call “_exit” function • Abnormal termination • Call “abort” function • Terminated by a signal
exit & _exit functions • Function prototype: #include <stdlib.h> void exit(int status); #include <unistd.h> void _exit(int status); • Exit status • Difference • _exit is corresponding to a system call, while “exit” is a library function. • _exit terminate a process immediately.
Exit handler • atexit function • Register a function to be called at normal program termination. • Prototype: #include <stdlib.h> int atexit(void (*function)(void)); • on_exit function • Example
The memory map of a C program • Text segment (code segment) • Data segment • Initialized data • Uninitialized data • Heap • Stack
Command line arguments • main function int main(int argc, char *argv[]); • Example: • The implementation of echo(1) • Command line option • Standard usage • getopt function
getopt function • Prototype: int getopt(int argc, char *const argv[], const char *optstring); extern char *optarg; extern int optind, opterr, optopt; • Question: • getopt(argc, argv, “if:lr”); • Program example (P104, in BLP)
Environment variables • Environment table • Environment pointer • extern char **environ;
putenv & getenv functions • Get, set or unset an environment variable #include <stdlib.h> char *getenv(const char *name); int putenv(char *string); int setenv(const char *name, const char *value, int overwirte); void unsetenv(const char *name);
Shared object • Shared object • Dynamic link • Advantages and disadvantages • Example • How to create a static and shared library? • How to use (link) a static or shared library?
Memory allocation • Allocate and free dynamic memory. #include <stdlib.h> void *malloc(size_t size); void *calloc(size_t nmemb, size_t size); void free(void *ptr); void realloc(void *ptr, size_t size);
2. Process control • Process identifier • System call “fork” • The simple synchronization between parent and child process • The “exec” function family • Example: • The implementation of a simple shell
fork • fork: create a child process #include <sys/types.h> #include <unistd.h> pid_t fork(void); • returned value: pid of child (in the current (parent) process), 0 (in child process), -1 (failure)
A simple example #include <stdio.h> #include <sys/types.h> #include <unistd.h> /* fork系统调用的第一个例子(不含错误检查)*/ void main() { printf(“Hello, world!\n”); fork(); printf(“bye\n”); }
The usage of “fork” • Code example if ( (pid=fork()) < 0) { /* error handling */ } else if (pid == 0) { /* child */ } else { /* parent */ }; • Program example • Program8-1 in APUE
File sharing • 所有由父进程打开的描述符都被复制到子进程中。父、子进程每个相同的打开描述符共享一个文件表项
vfork & clone functions • vfork #include <sys/types.h> #include <unistd.h> pid_t vfork(void); • clone #include <sched.h> int clone(int (*fn)(void *), void *child_stack, int flag, void *arg);
The simple synchronization between parent and child process • The relationship between parent and child process • wait and waitpid functions
The relationship between parent and child process • The parent terminates before the child • Orphan process • The child terminates before the parent • SIGCHLD signal • Handled by wait/waitpid in parent • Not handled by wait/wait in parent -> zombie
wait & waitpid functions • Wait for process termination • Prototype #include <sys/types.h> #include <sys/wait.h> pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options); • Example
Race condition int main(void){ pid_t pid; if ( (pid = fork()) < 0) err_sys("fork error"); else if (pid == 0) { charatatime("output cccccccccccc from child\n"); } else { charatatime("output pppppppppp from parent\n"); } exit(0); }
An improvement int main(void){ pid_t pid; TELL_WAIT(); if ( (pid = fork()) < 0) err_sys("fork error"); else if (pid == 0) { WAIT_PARENT(); /* parent goes first */ charatatime("output cccccccccccc from child\n"); } else { charatatime("output pppppppppp from parent\n"); TELL_CHILD(pid); } exit(0); }
The “exec” family of functions • Replace the current process image with a new process image. • 执行新程序的进程保持原进程的一系列特征: • pid, ppid, uid, gid, working directory, root directory … • euid/egid? • 打开文件描述符?
Functions prototypes #include <unistd.h> extern char **environ; int execl(const char *path, const char *arg, ...); int execlp(const char *file, const char *arg, ...); int execle(const char *path, const char *arg, ..., char * const envp[]); int execv(const char *path, char * const argv[]); int execvp(const char *file, char * const argv[]); #include <unistd.h> int execve(const char *filename, char * const argv[], char * const envp[]);
exec and opened file descriptor • close-on-exec bit of a file descriptor • Set by “fcntl” function fcntl(fd, F_SETFD, 0); /*系统默认, 打开文件描述符在 exec 时不关闭 */ fcntl(fd, F_SETFD, 1); /*打开文件描述符在 exec 时关闭 */
Using fork and exec together • Two ways of using fork • The parent process duplicates itself, and then two different pieces of codes are executed in parent process and child process. • A process want to execute another program. • Example: • The implementation of “system” function • int system(const char*cmdstring);
Example: a simple shell printf("%% "); /* print prompt */ while (fgets(buf, MAXLINE, stdin) != NULL) { buf[strlen(buf) - 1] = 0; /* replace newline with null */ if ( (pid = fork()) < 0 ) err_sys(“fork error”); else if ( pid == 0 ) { /* child */ execlp(buf, buf, (char *) 0); fprintf(stderr, "couldn't execute: %s", buf); exit(127); } if ( (pid = waitpid(pid, &status, 0)) < 0 ) /* parent */ err_sys(“waitpid error”); printf("%% "); }
3. Process relationship • 父进程和子进程 • 进程树 • ps, pstree命令
Startup & login (1) • Login on serial terminal
Startup & login (2) • Network login
Process group & session • Process group • The set of one or more process(es). • getpgrp/setpgid functions • Session • The set of one or more process group(s). • setsid function • Controlling terminal • Why are they introduced? • Job control
4. Signal • The concept of signals • The “signal” function • Send a signal • kill, raise • The “alarm” and “pause” functions • Reliable signal mechanism
The concept of signals • Signal • Software interrupt • Mechanism for handling asynchronous events • Having a name (beginning with SIG) • Defined as a positive integer (in <signal.h>) • How to produce a signal • 按终端键,硬件异常,kill(2)函数,kill(1)命令,软件条件,...
Signal handling • 忽略信号 • 不能忽略的信号: • SIGKILL, SIGSTOP • 一些硬件异常信号 • 执行系统默认动作 • 捕捉信号