linux进程间通信——深入理解linux信号量( 五 )

注:读者可以尝试一下注释掉初始化步骤,进程在运行时会出现何种情况(进程在申请资源时会睡眠),同时可以像程序结尾给出的注释那样,把该程序编译成两个不同版本 。下面是本程序的运行结果(操作系统gentoo):
create semaphore success, initialize itowner's uid is 1007owner's gid is 1007creater's uid is 1007creater's gid is 1007the number of entries in semaphore map is 32000 max number of semaphore identifiers is 128 mas number of semaphores in system is 32000 the number of undo structures system wide is 32000 max number of semaphores per gi_semid is 250 max number of ops per semop call is 32 max number of undo entries per process is 32 the sizeof of struct sem_undo is 20 the maximum semaphore value is 32767 before semop, semun_arg.buf->sem_otime: 0now ask the resourceask the resource successafter semop, semun_arg.buf->sem_otime: 1398501342now free the resourceremove sem okSummary:信号灯与其它进程间通信方式有所不同,它主要用于进程间同步 。通常所说的系统V信号灯实际上是一个信号灯的集合,可用于多种共享资源的进程间同步 。每个信号灯都有一个值,可以用来表示当前该信号灯代表的共享资源可用(available)数量,如果一个进程要申请共享资源,那么就从信号灯值中减去要申请的数目,如果当前没有足够的可用资源,进程可以睡眠等待,也可以立即返回 。当进程要申请多种共享资源时,linux可以保证操作的原子性,即要么申请到所有的共享资源,要么放弃所有资源,这样能够保证多个进程不会造成互锁 。Linux对信号灯有各种各样的限制,程序中给出了输出结果 。另外,如果读者想对信号灯作进一步的理解,建议阅读sem.h源代码,该文件不长,但给出了信号灯相关的重要数据结构 。




推荐阅读