04第四章互斥同步与通讯1
Linux共享内存通讯(例子) 接收进程 rcvshm.c #include #include #include #include #include #include main() { int shmid; char *viraddr; Linux共享内存通讯(例子) shmid=shmget(1234,BUFSIZ,0666|IPC_CREAT) viraddr=shmat(shmid, 0,SHM_RDONLY); printf("Your message is :\n%s",viraddr); shmdt(viraddr); shmctl(shmid,IPC_RMID,0); exit(0); } Linux共享内存(例2) #include #include #include #define KEY 1234 #define SIZE 1024 int main() { int shmid; char *shmaddr; struct shmid_ds buf; shmid = shmget(KEY, SIZE, IPC_CREAT | 0600); /*建立共享内存*/ if (fork() == 0) { shmaddr = (char *) shmat(shmid, 0, 0); strcpy(shmaddr, "Hi! I am Chiled process!/n"); printf("Child: write to shared memery: /"Hi! I am Chiled process!/"/n"); shmdt(shmaddr); return; } Linux共享内存(例2) else { sleep(3); /*等待子进程执行完毕*/ shmctl(shmid, IPC_STAT, &buf); /*取得共享内存的状态*/ printf("shm_segsz = %d bytes/n", buf.shm_segsz); printf("shm_cpid = %d/n", buf.shm_cpid); printf("shm_lpid = %d/n", buf.shm_lpid); shmaddr = (char*) shmat(shmid, 0, SHM_RDONLY); printf("Father: %s/n", shmaddr); /*显示共享内存内容*/ shmdt(shmaddr); shmctl(shmid, IPC_RMID, NULL); /*删除共享内存*/ } } Linux共享存储通讯 几点说明 fork()后子进程继承其父进程已连接的共享内存; 执行execl自动剥离共享存储; 执行exit自动剥离共享存储。 4.4 进程高级通讯 进程通讯:进程之间的相互作用。 低级通讯(简单信号) 进程互斥 进程同步 高级通讯(大宗信息) 高级通讯 memory sharing vs. message passing direct vs. indirect symmetric vs. non-symmetric buffering vs. non-buffering 4.4.1 进程通讯概念 4.4.2 进程通讯模式 1. 共享内存模式(shared memory): 2. 消息传递模式(message passing): OS提供: (1)公共内存 (2)互斥同步机制 P1 P2 M send receive 直接:进程-进程 间接:进程-信箱-进程 P1 P2 公共内存 4.4.3 直接方式 对称形式(sender and receiver name each other) send(R,message) receive(S,message) … Send(R,M) ... … Receive(S,