Linux高级编程英文版.pdf

上传人:qwe****56 文档编号:69996743 上传时间:2023-01-13 格式:PDF 页数:372 大小:5.64MB
返回 下载 相关 举报
Linux高级编程英文版.pdf_第1页
第1页 / 共372页
Linux高级编程英文版.pdf_第2页
第2页 / 共372页
点击查看更多>>
资源描述

《Linux高级编程英文版.pdf》由会员分享,可在线阅读,更多相关《Linux高级编程英文版.pdf(372页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。

1、Exported ProjectsG Advanced Linux Programmingfile:/C|/Export/contents.htm 3/11/2003 11:54:44 AM Advanced Linux ProgrammingAdvanced Linux Programming TitleFile Filesize md5 checksum Front Matter and Table of Contentspdf 1273361 fe0c601b919879e93d79d25a78818b5c Chapter 01-Advanced Unix Programming wit

2、h Linuxpdf235835 5923f2a5d7fb4f941fe905fbe45be196 Chapter 02-Writting Good GNU/Linux Softwarepdf280326 44c823c1240c7f70a6dc9dbfddbe03fa Chapter 03-Processespdf241758 87b5d98ba5b5933cf2ad1dbcf37641aa Chapter 04-Threadspdf292419 11f392b44c073498e9ec9b3f718e54e7 Chapter 05-Interprocess Communicationpdf

3、289853 0de9b56476a0e6e536fbac68e09b02d2 Chapter 06-Mastering Linuxpdf268821 ab8940fbcc40018d72bd2016e662afba Chapter 07-The/proc File Systempdf258582 b3fe701f67a37ad7ba7233bcdc3f5d90 Chapter 08-Linux System Callspdf 261352 583182dc09bc8b3c3773ba6d0fc710f2 Chapter 09-Inline Assembly Codepdf 204992 c2

4、26e58fc7bf544df477d8ae96b680ed Chapter 10-Securitypdf 288441 fc340b97e9c7f3fc2f5fe4dd71132ffd file:/C|/Export/ of 2)3/11/2003 11:54:48 AMDownload Advanced Linux ProgrammingChapter 11-A Sample GNU/Linux Applicationpdf298215 50a205644e441ae26d2041567d131b82 Appendix A-Other Development Toolspdf 272377

5、 09a9a79a3c3abe6869df3f1ab5b39b14 Appendix B-Low Level I/Opdf 252755 3eaa0f0bbd103e1cc7872663e227a14b Appendix C-Table of Signalspdf 177879 3b02a6abb38877580b743392b98c3290 Appendix D-Online Resourcespdf148074 372964ff1eb4f85aca3985736a06cc48 Appendix E-Open Publication License Version 1.0pdf176596

6、5b1ddb8d38b6a44b357345ba6c25010e Appendix F-The GNU General Public Licensepdf228793 e207c51489e6f3cfafba5b13bb5e3bd9 Indexpdf 1253094 004eefcfc2c6dca9a21233e748b81f35 Interprocess Communication5CHAPTER3,“PROCESSES,”DISCUSSED THE CREATION OF PROCESSESand showedhow one process can obtain the exit stat

7、us of a child process.Thats the simplest formof communication between two processes,but its by no means the most powerful.Themechanisms of Chapter 3 dont provide any way for the parent to communicate withthe child except via command-line arguments and environment variables,nor any wayfor the child t

8、o communicate with the parent except via the childs exit status.Noneof these mechanisms provides any means for communicating with the child processwhile it is actually running,nor do these mechanisms allow communication with aprocess outside the parent-child relationship.This chapter describes means

9、 for interprocess communication that circumvent theselimitations.We will present various ways for communicating between parents and chil-dren,between“unrelated”processes,and even between processes on differentmachines.Interprocess communication(IPC)is the transfer of data among processes.For example

10、,a Web browser may request a Web page from a Web server,which then sends HTMLdata.This transfer of data usually uses sockets in a telephone-like connection.Inanother example,you may want to print the filenames in a directory using a commandsuch as ls|lpr.The shell creates an lsprocess and a separate

11、 lprprocess,connecting06 0430 CH05 5/22/01 10:22 AM Page 9596Chapter 5 Interprocess Communicationthe two with a pipe,represented by the“|”symbol.A pipe permits one-way commu-nication between two related processes.The lsprocess writes data into the pipe,andthe lprprocess reads data from the pipe.In t

12、his chapter,we discuss five types of interprocess communication:nShared memory permits processes to communicate by simply reading and writing to a specified memory location.nMapped memory is similar to shared memory,except that it is associated with afile in the filesystem.nPipes permit sequential c

13、ommunication from one process to a related process.nFIFOs are similar to pipes,except that unrelated processes can communicatebecause the pipe is given a name in the filesystem.nSockets support communication between unrelated processes even on differentcomputers.These types of IPC differ by the foll

14、owing criteria:nWhether they restrict communication to related processes(processes with acommon ancestor),to unrelated processes sharing the same filesystem,or to anycomputer connected to a networknWhether a communicating process is limited to only write data or only read datanThe number of processe

15、s permitted to communicatenWhether the communicating processes are synchronized by the IPCfor example,a reading process halts until data is available to readIn this chapter,we omit discussion of IPC permitting communication only a limitednumber of times,such as communicating via a childs exit value.

16、5.1Shared MemoryOne of the simplest interprocess communication methods is using shared memory.Shared memory allows two or more processes to access the same memory as if they allcalled mallocand were returned pointers to the same actual memory.When oneprocess changes the memory,all the other processe

17、s see the modification.5.1.1Fast Local CommunicationShared memory is the fastest form of interprocess communication because allprocesses share the same piece of memory.Access to this shared memory is as fast asaccessing a processs nonshared memory,and it does not require a system call or entryto the

18、 kernel.It also avoids copying data unnecessarily.06 0430 CH05 5/22/01 10:22 AM Page 96975.1Shared MemoryBecause the kernel does not synchronize accesses to shared memory,you must pro-vide your own synchronization.For example,a process should not read from thememory until after data is written there

19、,and two processes must not write to the samememory location at the same time.A common strategy to avoid these race conditionsis to use semaphores,which are discussed in the next section.Our illustrative pro-grams,though,show just a single process accessing the memory,to focus on the sharedmemory me

20、chanism and to avoid cluttering the sample code with synchronizationlogic.5.1.2The Memory ModelTo use a shared memory segment,one process must allocate the segment.Then eachprocess desiring to access the segment must attach the segment.After finishing its useof the segment,each process detaches the

21、segment.At some point,one process mustdeallocate the segment.Understanding the Linux memory model helps explain the allocation and attach-ment process.Under Linux,each processs virtual memory is split into pages.Eachprocess maintains a mapping from its memory addresses to these virtual memory pages,

22、which contain the actual data.Even though each process has its own addresses,multipleprocessesmappings can point to the same page,permitting sharing of memory.Memory pages are discussed further in Section 8.8,“The mlockFamily:LockingPhysical Memory,”of Chapter 8,“Linux System Calls.”Allocating a new

23、 shared memory segment causes virtual memory pages to be cre-ated.Because all processes desire to access the same shared segment,only one processshould allocate a new shared segment.Allocating an existing segment does not createnew pages,but it does return an identifier for the existing pages.To per

24、mit a processto use the shared memory segment,a process attaches it,which adds entries mappingfrom its virtual memory to the segments shared pages.When finished with the seg-ment,these mapping entries are removed.When no more processes want to accessthese shared memory segments,exactly one process m

25、ust deallocate the virtual memory pages.All shared memory segments are allocated as integral multiples of the systems pagesize,which is the number of bytes in a page of memory.On Linux systems,the pagesize is 4KB,but you should obtain this value by calling the getpagesizefunction.5.1.3AllocationA pr

26、ocess allocates a shared memory segment using shmget(“SHared MemoryGET”).Its first parameter is an integer key that specifies which segment to create.Unrelated processes can access the same shared segment by specifying the same keyvalue.Unfortunately,other processes may have also chosen the same fix

27、ed key,whichcould lead to conflict.Using the special constant IPC_PRIVATEas the key value guaran-tees that a brand new memory segment is created.06 0430 CH05 5/22/01 10:22 AM Page 9798Chapter 5 Interprocess CommunicationIts second parameter specifies the number of bytes in the segment.Because seg-me

28、nts are allocated using pages,the number of actually allocated bytes is rounded upto an integral multiple of the page size.The third parameter is the bitwise or of flag values that specify options to shmget.The flag values include these:nIPC_CREATThis flag indicates that a new segment should be crea

29、ted.This per-mits creating a new segment while specifying a key value.nIPC_EXCLThis flag,which is always used with IPC_CREAT,causes shmgetto failif a segment key is specified that already exists.Therefore,it arranges for the call-ing process to have an“exclusive”segment.If this flag is not given and

30、 the keyof an existing segment is used,shmgetreturns the existing segment instead ofcreating a new one.nMode flagsThis value is made of 9 bits indicating permissions granted toowner,group,and world to control access to the segment.Execution bits areignored.An easy way to specify permissions is to us

31、e the constants defined inand documented in the section 2 statman page.1For example,S_IRUSRand S_IWUSRspecify read and write permissions for the owner of theshared memory segment,and S_IROTHand S_IWOTHspecify read and write per-missions for others.For example,this invocation of shmgetcreates a new s

32、hared memory segment(oraccess to an existing one,if shm_keyis already used)thats readable and writeable tothe owner but not other users.int segment_id=shmget(shm_key,getpagesize(),IPC_CREAT|S_IRUSR|S_IWUSER);If the call succeeds,shmgetreturns a segment identifier.If the shared memory segmentalready

33、exists,the access permissions are verified and a check is made to ensure thatthe segment is not marked for destruction.5.1.4Attachment and DetachmentTo make the shared memory segment available,a process must use shmat,“SHaredMemory ATtach.”Pass it the shared memory segment identifier SHMIDreturned b

34、yshmget.The second argument is a pointer that specifies where in your processs addressspace you want to map the shared memory;if you specify NULL,Linux will choosean available address.The third argument is a flag,which can include the following:nSHM_RNDindicates that the address specified for the se

35、cond parameter should berounded down to a multiple of the page size.If you dont specify this flag,youmust page-align the second argument to shmatyourself.nSHM_RDONLYindicates that the segment will be only read,not written.1.These permission bits are the same as those used for files.They are describe

36、d in Section10.3,“File System Permissions.”06 0430 CH05 5/22/01 10:22 AM Page 98995.1Shared MemoryIf the call succeeds,it returns the address of the attached shared segment.Children cre-ated by calls to forkinherit attached shared segments;they can detach the sharedmemory segments,if desired.When yo

37、ure finished with a shared memory segment,the segment should bedetached using shmdt(“SHared Memory DeTach”).Pass it the address returned byshmat.If the segment has been deallocated and this was the last process using it,it isremoved.Calls to exitand any of the execfamily automatically detach segment

38、s.5.1.5Controlling and Deallocating Shared MemoryThe shmctl(“SHared Memory ConTroL”)call returns information about a sharedmemory segment and can modify it.The first parameter is a shared memory segmentidentifier.To obtain information about a shared memory segment,pass IPC_STATas the second argument

39、 and a pointer to a struct shmid_ds.To remove a segment,pass IPC_RMIDas the second argument,and pass NULL as thethird argument.The segment is removed when the last process that has attached itfinally detaches it.Each shared memory segment should be explicitly deallocated using shmctlwhenyoure finish

40、ed with it,to avoid violating the systemwide limit on the total number ofshared memory segments.Invoking exitand execdetaches memory segments butdoes not deallocate them.See the shmctlman page for a description of other operations you can perform onshared memory segments.5.1.6An Example ProgramThe p

41、rogram in Listing 5.1 illustrates the use of shared memory.Listing 5.1(shm.c)Exercise Shared Memory#include#include#include int main()int segment_id;char*shared_memory;struct shmid_ds shmbuffer;int segment_size;const int shared_segment_size=0 x6400;/*Allocate a shared memory segment.*/segment_id=shm

42、get(IPC_PRIVATE,shared_segment_size,IPC_CREAT|IPC_EXCL|S_IRUSR|S_IWUSR);continues06 0430 CH05 5/22/01 10:22 AM Page 99100Chapter 5 Interprocess Communication/*Attach the shared memory segment.*/shared_memory=(char*)shmat(segment_id,0,0);printf(“shared memory attached at address%pn”,shared_memory);/*

43、Determine the segments size.*/shmctl(segment_id,IPC_STAT,&shmbuffer);segment_size=shmbuffer.shm_segsz;printf(“segment size:%dn”,segment_size);/*Write a string to the shared memory segment.*/sprintf(shared_memory,“Hello,world.”);/*Detach the shared memory segment.*/shmdt(shared_memory);/*Reattach the

44、 shared memory segment,at a different address.*/shared_memory=(char*)shmat(segment_id,(void*)0 x5000000,0);printf(“shared memory reattached at address%pn”,shared_memory);/*Print out the string from shared memory.*/printf(“%sn”,shared_memory);/*Detach the shared memory segment.*/shmdt(shared_memory);

45、/*Deallocate the shared memory segment.*/shmctl(segment_id,IPC_RMID,0);return 0;5.1.7DebuggingThe ipcscommand provides information on interprocess communication facilities,including shared segments.Use the-mflag to obtain information about shared memory.For example,this code illustrates that one sha

46、red memory segment,numbered 1627649,is in use:%ipcs-m-Shared Memory Segments-key shmid owner perms bytes nattch status0 x00000000 1627649 user 640 25600 0If this memory segment was erroneously left behind by a program,you can use theipcrmcommand to remove it.%ipcrm shm 1627649Listing 5.1Continued06

47、0430 CH05 5/22/01 10:22 AM Page 1001015.2Processes Semaphores5.1.8Pros and ConsShared memory segments permit fast bidirectional communication among any numberof processes.Each user can both read and write,but a program must establish and fol-low some protocol for preventing race conditions such as o

48、verwriting informationbefore it is read.Unfortunately,Linux does not strictly guarantee exclusive access evenif you create a new shared segment with IPC_PRIVATE.Also,for multiple processes to use a shared segment,they must make arrangementsto use the same key.5.2Processes SemaphoresAs noted in the p

49、revious section,processes must coordinate access to shared memory.As we discussed in Section 4.4.5,“Semaphores for Threads,”in Chapter 4,“Threads,”semaphores are counters that permit synchronizing multiple threads.Linux provides adistinct alternate implementation of semaphores that can be used for s

50、ynchronizingprocesses(called process semaphores or sometimes System V semaphores).Process sem-aphores are allocated,used,and deallocated like shared memory segments.Although asingle semaphore is sufficient for almost all uses,process semaphores come in sets.Throughout this section,we present system

展开阅读全文
相关资源
相关搜索

当前位置:首页 > 技术资料 > 其他杂项

本站为文档C TO C交易模式,本站只提供存储空间、用户上传的文档直接被用户下载,本站只是中间服务平台,本站所有文档下载所得的收益归上传人(含作者)所有。本站仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。若文档所含内容侵犯了您的版权或隐私,请立即通知淘文阁网,我们立即给予删除!客服QQ:136780468 微信:18945177775 电话:18904686070

工信部备案号:黑ICP备15003705号© 2020-2023 www.taowenge.com 淘文阁