170 likes | 359 Views
Linux Programming – Process & Signal. Reporter: Po-Sen Wang. 起始新程序 (1/2). #include <stdlib.h> int system(const char * string ); Example. 起始新程序 (2/2). 使用 system 函數在背景執行 Example. 程序的替換 (1/3). #include <unistd.h> extern char **environ;
E N D
Linux Programming – Process & Signal Reporter: Po-Sen Wang
起始新程序 (1/2) • #include <stdlib.h> • int system(const char *string); • Example Po-Sen Wang
起始新程序 (2/2) • 使用 system 函數在背景執行 • Example Po-Sen Wang
程序的替換 (1/3) • #include <unistd.h> • extern char **environ; • int execl(const char *path, const char *arg0, ..., (char *) 0); • int execlp(const char *file, const char *arg0, ..., (char *) 0); • int execle(const char *path, const char *arg0, ..., (char *) 0, const char *envp[]); • int execv(const char *path, const char *argv[]); • int execvp(const char *file, const char *argv[]); • int execve(const char *path, const char *argv[], const char *envp[]); Po-Sen Wang
程序的替換 (2/3) • 使用 exec 函數來起始 ps 程式: • const char *ps_argv[]={“ps”, “-ax”, 0}; • const char *ps_envp[]= {“PATH=/bin:/usr/bin”, “TERM=console”, 0}; • execl(“/bin/ps”, “ps”, “-ax”, 0); • execlp(“ps”, “ps”, “-ax”, 0); • execle(“/bin/ps”, “ps”, “-ax”, 0, ps_envp); • execv(“/bin/ps”, ps_argv); • execvp(“ps”, ps_argv); • execve(“/bin/ps”, ps_argv, ps_evnp); Po-Sen Wang
程序的替換 (3/3) • Example Po-Sen Wang
複製程序 (1/2) • #include <sys/types.h> • #include <unistd.h> • pid_t fork(void); 起始程序 fork() 傳回子程序PID 傳回0 父始程序繼續執行 子程序 Po-Sen Wang
複製程序 (2/2) • Example Po-Sen Wang
等待程序 (1/2) • #include <sys/types.h> • #include <sys/wait.h> • pid_t wait(int *stat_val); • 巨集 Po-Sen Wang
等待程序 (2/2) Po-Sen Wang
Signal (1/2) • 一些會造成程序立即終止的訊號: Po-Sen Wang
Signal (2/2) • #include <signal.h> • void (*signal(int sig, void (*func)(int)))(int); • func可以自定,或是SIG_IGN(忽略訊息)、SIG_DFL(恢復預設的行為) • Example Po-Sen Wang
傳送訊息 (1/2) • #include <sys/types.h> • #include <signal.h> • int kill(pid_t pid, int sig); • #include <unistd.h> • unsigned int alarm(unsigned int seconds); Po-Sen Wang
傳送訊息 (2/2) Po-Sen Wang
Sigaction (1/2) • #include <signal.h> • int sigaction(int sig, const struct sigaction *act, struct sigaction *oact) • sigaction struct 的部分成員: void (*sa_handler)(int); //function, SIG_DFL, SIG_IGN sigset_t sa_mask; //signals to block in sa_handler int sa_flags; //signal action modifiers • sa_flags: Po-Sen Wang
Sigaction (2/2) Po-Sen Wang
作業 • 請撰寫一程式產生一子程序。 • 父程序分別印出父程序及子程序的id,並等待子程序傳送SIGALRM訊號。接收到SIGALRM訊號後,在營幕上印出”Child process finish.”訊息。 • 子程序去執行另一個1加到100的程式,並傳送SIGALRM訊號給父程序。 Po-Sen Wang