lap trinh he thong bkhn

92
Lương Ánh Hoàng Bộ môn Kỹ Thuật Máy Tính Đại học Bách Khoa Hà Nội Lập trình hệ thống

Upload: nguyen-linh

Post on 28-Sep-2015

229 views

Category:

Documents


5 download

DESCRIPTION

Slide Lap trinh he thong

TRANSCRIPT

Lp trnh h thng

Lng nh HongB mn K Thut My Tnhi hc Bch Khoa H NiLp trnh h thngGii thiuMc ch: Cung cp cc kin thc c bn v lp trnh h thng vi hai h h iu hnh thng dng nht:Microsoft WindowsLinuxYu cu:H iu hnhNgn ng lp trnh C.Ti liuLinux System Programming, Second Edition by Robert Love, 2013 OReilly Media.Windows System Programming (4th Edition) by Johnson (John) M. Hart, 2010 Addison-Wesley Microsoft Technology Series.MSDN Microsoft Development Network.Google , Bing.Stackoverflow.com

Ni dungGii thiu chungWindows APILinux Posix API2. Lp trnh h thng trn WindowsQun l tp tinInter Process CommunicationMemory ManagementPower ManagementQun l tin trnh v lungQun l dch vCc c ch ng bNi dung3. Lp trnh h thng trn LinuxMt s khi nim c bn.Vo ra tp tin.Qun l tin trnh.Qun l lung.Qun l b nh.Signal.Lng nh HongB mn K Thut My Tnhi hc Bch Khoa H Ni1.Gii thiu chung1.Gii thiu chungH iu hnh: Tp hp cc phn mm h thng qun l mt lot ti nguyn ca my tnh bao gm:B nh. Hin nay cc h iu hnh u qun l ton b b nh ca my tnh,bao gm RAM, HDD, CacheH thng tp tin.B vi x l.nh danh ti nguyn v khu vc.a nhim.Truyn thng v ng bAn ninh.1.Gii thiu chungGiao din lp trnh h thng: Tt c cc h iu hnh u cung cp cc giao din lp trnh cho ng dng:Windows API: Win16, Win32, Win32s, Win64. Nm trong cc tp tin : kernel32.dll, user32.dll, gdi32.dll.Linux ABI/API

Lng nh HongB mn K Thut My Tnhi hc Bch Khoa H Ni2.Lp trnh h thng trn Linux2.1.Mt s khi nim c bnMt s thut ng khi lp trnh:Li gi h thng System CallCc hm c gi t userspace sang kernel space yu cu dch v hoc ti nguyn t h iu hnh. Th d: read(), write(),get_thread_area()Vic chuyn i ng cnh c thc hin qua ngt (software interrupt). Cc tham s c truyn qua thanh ghi. VD: vi CPU i386 l ngt 80h.Th vin Clibc, glibc tri tim ca mi ng dng unix.Cung cp li gi h thng, v cc dch v c bn khc.Trnh bin dch CGNU Compiler Collection (GCC)

2.1.Mt s khi nim c bnMt s thut ng khi lp trnh:APIGiao din lp trnh mc cao (m ngun).Cho php cc phn mm tng tc vi nhau.ABIGiao din mc thp (binary) gia cc phn mm trn mt kin trc c th.VD: Cch mt chng trnh tng tc vi h iu hnh, vi mt th vin khc.m bo chng trnh c th thc thi trn h thng khc c ABI tng thch.c t cc tiu chun nh: calling convention, byte ordering, register use, system call, linking,..khun dng file object.

2.1.Mt s khi nim c bnMt s thut ng khi lp trnh:POSIXPortable Operating System Interface Mt chun ca IEEE nhm thng nht giao din mc thp trong cc h iu hnh h Unix.Ngn ng Cc chun ha bi ANSI v ISO.Phin bn mi nht ISO C11X l m liPhn ln cc hm u tr v -1 nu c li.M li c lu trong bin errno#include extern int errno;

2.2. Vo ra tp tinM tp tinNguyn mu v th d#include #include #include int open (const char *name, int flags);int open (const char *name, int flags, mode_t mode); int fd; fd = open ("/home/kidd/madagascar", O_RDONLY); if (fd == 1)/* error */ Cc c khi m: O_APPEND | O_ASYNC | O_CLOEXEC | O_CREAT | O_DIRECT | O_DIRECT | O_DIRECTORY | O_EXCL | O_LARGEFILEOwner ca tp tin mi: effective UID ca tin trnh to ra file .Permission ca tp tin mi: mode. V d: 0x0666Vo ra trc tip O_DIRECT: B qua cc c ch b m ca h thng. Tc chm hn.

2.2.Qun l tp tinc tp tinNguyn mu v th d#include ssize_t read (int fd, void *buf, size_t len);unsigned long word; ssize_t nr;// 32-bit or 64-bit /* read a couple bytes into 'word' from 'fd' */nr = read (fd, &word, sizeof (unsigned long)); if (nr == 1)/* error */Gi tr tr v: S byte c c nu thnh cng, c th t hn nr.0 nu EOF-1 nu c li hoc b ngt (EINTR)

2.2.Qun l tp tinGhi tp tinNguyn mu v th d#include ssize_t write (int fd, const void *buf, size_t count); const char *buf = "My ship is solid!"; ssize_t nr; /* write the string in 'buf' to 'fd' */ nr = write (fd, buf, strlen (buf)); if (nr == 1) /* error */

Gi tr tr v: S byte ghi c nu thnh cng, c th t hn nr.-1 nu c li hoc b ngt (EINTR)

2.2.Qun l tp tinng b d liu ln aNguyn mu v th d#include int fsync (int fd); int ret;ret = fsync (fd);

Gi tr tr v: 0 nu thnh cng.-1 nu c li.

2.2.Qun l tp tinTruy nhp n v tr bt k trong fileNguyn mu v th d#include #include off_t lseek (int fd, off_t pos, int origin);off_t ret; ret = lseek (fd, (off_t) 1825, SEEK_SET); if (ret == (off_t) 1) /* error */

origin c th l: SEEK_SET, SEEK_END, SEEK_CUR.Gi tr tr v: Thnh cng: v tr mi ca con tr tp tin.Tht bi : -1.C th gi lseek(fd, (off_t) 0, SEEK_CUR) ly v v tr hin ti ca tp tin.Ly kch thc file ?

2.2. Vo ra tp tinScatter/Gather I/ONguyn mu#include ssize_t readv (int fd,const struct iovec *iov, int count);ssize_t writev (int fd,const struct iovec *iov, int count);

struct iovec {void *iov_base; /* pointer to start of buffer */ size_t iov_len; /* size of buffer in bytes */ }; Gi tr tr v: Thnh cng: Tng s byte c c hoc ghi.Tht bi : -1.Th d: Xem code

2.2. Vo ra tp tinThm d s kin vi Even PollNguyn mu#include struct epoll_event {__u32 events; // EPOLLIN | EPOLLOUT union {void *ptr; int fd; __u32 u32; __u64 u64; } data;}int epoll_create1 (int flags); int epoll_ctl (int epfd, int op,// EPOLL_CTL_ADD,EPOLL_CTL_DEL,EPOLL_CTL_MODint fd,// STDIN_FILEFD,STDOUT_FILEFD,STDERR_FILEFDstruct epoll_event *event); int epoll_wait (int epfd,struct epoll_event *events, int maxevents,int timeout);

2.2. Vo ra tp tinThm d s kin vi Event PollCch s dng1.To i tng epoll qua hm epoll_create1 => epoll_fd2.Vi mi file fd cn thm d, khai bo mt cu trc epoll_event v khi to gi tr thch hp.3.Thm cu trc epoll_event va khai bo vo i tng epoll_fd.4.Gi hm epoll_wait thm d s kin trn tt c cc fd. Kt qu l con tr tr n cu trc epoll_event c s kin..5.X l s kin trn file tng ng. Lu Event Poll cho hiu nng cao hn nhiu so vi select v poll v kernel khng phi duyt ht danh sch cc fd mi khi c s kin.Event Poll ch c trn kernel 2.6 tr ln.

2.2. Vo ra tp tinThm d s kin vi Event PollTh dchar buffer[1024];int ret,len;struct epoll_event stdin_event;int epfd = epoll_create1(0);stdin_event.data.fd = STDIN_FILENO; // c t bn phmstdin_event.events = EPOLLIN;epoll_ctl(epfd,EPOLL_CTL_ADD,STDIN_FILENO,&stdin_event);epoll_event event; while (1) { ret = epoll_wait(epfd,&event,1,1000); if (ret == 0) { printf(Timeout!\n"); continue; } len = read(event.data.fd,buffer,1024); if (len>0) { buffer[len] = 0; printf("%s",buffer); } }

2.2. Vo ra tp tinnh x tp tin vo trong b nhNguyn mu#include void * mmap (void *addr, // Hint, thng l 0size_t len, int prot, int flags, int fd,off_t offset); int munmap (void *addr, size_t len);

Tham s prot: memory protection, c th nhn cc gi tr: PROT_READ | PROT_WRITE | PROT_EXEC.Tham s flags: kiu mapping, c th l MAP_FIXED, MAP_PRIVATE, MAP_SHARED.Gi tr tr v: Thnh cng: a ch c map. Nm chn trn mt hoc nhiu trang b nh (page).Tht bi : MAP_FAILED. M li nm trong errno.

2.2. Vo ra tp tinnh x tp tin vo trong b nhMinh ha

Th dvoid *p; p = mmap (0, len, PROT_READ, MAP_SHARED, fd, 0); if (p == MAP_FAILED) perror ("mmap");munmap(p,len); // Un-map

2.2. Vo ra tp tinnh x tp tin vo trong b nhTng, gim kch thc mapping: mremap#include void * mremap (void *addr, size_t old_size,size_t new_size, unsigned long flags); C flags: 0 hoc MREMAP_MAYMOVE (tng c hi thnh cng) Gi tr tr v:Thnh cng: a ch miTht bi: MAP_FAILED. M li nm trong errno

2.2. Vo ra tp tinnh x tp tin vo trong b nhThay i c ch bo v b nh: mprotect#include int mprotect (const void *addr, size_t len, int prot);

C prot: PROT_NONE, PROT_READ, PROT_WRITE, PROT_EXEC Gi tr tr v:Thnh cng: 0Tht bi: -1. M li nm trong errno

2.3.Qun l tin trnhTin trnhL mt chng trnh ang chy trong b nh.c nh danh bi Process ID (pid).Tin trnh c t chc phn cp.Mi tin trnh u c parent process v c th c child process.Ch s hu tin trnh l user v groupTin ch top hoc htop dng xem thng tin v tin trnh.Ly nh danh tin trnhNguyn mu#include #include pid_t getpid (void);pid_t getppid (void);Th dprintf ("My pid=%jd\n", (intmax_t) getpid ());printf ("Parent's pid=%jd\n", (intmax_t) getppid ());

2.3.Qun l tin trnhKhi chy mt tin trnh miNguyn mu#include // H execint 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[]); int execve (const char *filename, char *const argv[],char *const envp[]); // forkpid_t fork (void);Th d execlint ret; ret = execl("/bin/vi", "vi", "/home/encoder/helloworld.c", NULL); if (ret == 1) perror ("execl");

2.3.Qun l tin trnhKhi chy mt tin trnh miTh d forkpid_t pid; pid = fork (); if (pid > 0) printf ("I am the parent of pid=%d!\n", pid); else if (!pid) printf ("I am the child of pid %d!\n",getppid()); Tiin trnh con mi sau khi fork s tip tc chy song song vi tin trnh cha ban u.

2.3.Qun l tin trnhi tin trnh con kt thcNguyn mu#include #include pid_t wait (int *status);// i cho n khi mt tin trnh con kt thcpid_t waitpid (pid_t pid, int *status, int options);

Hm wait: Gi tr tr v l Process ID ca tin trnh con va kt thc v *status cha thng tin v l do kt thc ca tin trnh con. Cc macro sau gip trch xut thng tin :int WIFEXITED (status); int WIFSIGNALED (status); int WIFSTOPPED (status); int WIFCONTINUED (status); int WEXITSTATUS (status); int WTERMSIG (status); int WSTOPSIG (status); int WCOREDUMP (status);

2.3.Qun l tin trnhi tin trnh con kt thcHm waitpid : i mt tin trnh con c th kt thc. Cch x l ging nh wait. Mt s ty chn khc c th xem thm trong sch.Nu tin trnh cha kt thc trc tin trnh con th tin trnh con s c cha mi l tin trnh init

2.3.Qun l tin trnhUser v GroupMi tin trnh c bn user ID: real user ID, effective user ID, saved user ID, v filesystem user ID.Effective user ID dng xc thc , kim sot truy nhp n ti nguyn ca tin trnh.ng dng c th gi hm setuid hoc setgid thay i effective user ID v effective group ID.Process PrioritiesMc u tin ca tin trnh.Thay i qua hm nice, getpriority, setpriority#include int nice (int inc); int getpriority (int which, int who);int setpriority (int which, int who, int prio); Cn permission CAP_SYS_NICE (root)

2.3.Qun l tin trnhProcessor AffinityThay i phn phi ti nguyn CPU cho tin trnh (la chn s s dng li CPU no chy tin trnh).Cc nguyn mu

#include

typedef struct cpu_set_t; size_t CPU_SETSIZE;

void CPU_SET (unsigned long cpu, cpu_set_t *set); void CPU_CLR (unsigned long cpu, cpu_set_t *set); int CPU_ISSET (unsigned long cpu, cpu_set_t *set); void CPU_ZERO (cpu_set_t *set);

int sched_setaffinity (pid_t pid, size_t setsize, const cpu_set_t *set);

int sched_getaffinity (pid_t pid, size_t setsize, cpu_set_t *set);

2.4.Qun l lungLung Threadn v thc thi ca tin trnh trn mt CPU o.Pthread API nm trong th vin glibc cha tt c cc hm cn thit Qun l lung.ng b gia cc lung.Mi chng trnh khi chy u c mt lung mc nh: master thread v bt u hm mainNguyn mu:#include int pthread_create (pthread_t *thread,const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);

void * start_thread (void *arg); Gi tr tr v:Thnh cng: 0Tht bi: m li trc tip (khng cn ly t errno) Lu : Cn phi link vi th vin pthread mt cch tng minh.

2.4.Qun l lungLung ThreadTh d:pthread_t tread; int ret; ret = pthread_create (&thread, NULL, start_routine, NULL); if (!ret) { errno = ret; perror("pthread_create"); return -1; } /* a new thread is created and running start_routine concurrently ... */

2.4.Qun l lungnh danh lungnh danh lung: Thread ID tng t nh Process ID.Ly nh danh lung : pthread_t pthread_self()So snh lung:int pthread_equal (pthread_t t1, pthread_t t2);V dint ret; ret = pthread_equal(thing1, thing2); if (ret != 0) printf("The TIDs are equal!\n"); else printf("The TIDs are unequal!\n");

2.4.Qun l lungKt thc mt lungLung t kt thc khi khng cn vic g lm.Khi gi hm pthread_exit() trong chnh lung .Khi b kt thc bi lung khc qua hm pthread_cancel().Khi b kt thc bi lung khc qua pthread_kill() : nguy him

2.4.Qun l lungng b lungRace condition: xy ra khi hai hoc nhiu lung cng truy nhp n mt ti nguyn.V d:int x = 0,i,j;void * thread_1(void*param){for (i=0;i