[国嵌攻略][084][信号同步编程]
生活随笔
收集整理的這篇文章主要介紹了
[国嵌攻略][084][信号同步编程]
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
進(jìn)程同步
一組并發(fā)進(jìn)程進(jìn)行相互合作、相互等待,使得各進(jìn)程按一定的順序執(zhí)行的過(guò)程稱為進(jìn)程間的同步。
?
進(jìn)程同步與進(jìn)程互斥
進(jìn)程同步問(wèn)題的關(guān)鍵在于生產(chǎn)者不需要獲取信號(hào)量,消費(fèi)者不需要釋放信號(hào)量,所以信號(hào)量的初值設(shè)置為0。但是進(jìn)程互斥問(wèn)題中雙方都需要獲取和釋放信號(hào)量,所以信號(hào)量的初值至少為1。
?
producor.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h>#include <sys/ipc.h> #include <sys/sem.h>void main(){//創(chuàng)建文件int fd;fd = open("product.txt", O_RDWR | O_CREAT, 0777);//睡眠等待sleep(10);//寫(xiě)入數(shù)據(jù)write(fd, "The product is finished!", 25);//關(guān)閉文件 close(fd);//創(chuàng)建信號(hào)量int key;int semid;key = ftok("product.txt", 0);semid = semget(key, 1, IPC_CREAT);//設(shè)置信號(hào)量semctl(semid, 0, SETVAL, 0); //設(shè)置信號(hào)量0的值為0//釋放信號(hào)量struct sembuf sops;sops.sem_num = 0;sops.sem_op = 1;sops.sem_flg = SEM_UNDO;semop(semid, &sops, 1); }?
customer.c
#include <stdlib.h>#include <sys/ipc.h> #include <sys/sem.h>void main(){//打開(kāi)信號(hào)量int key;int semid;key = ftok("product.txt", 0);semid = semget(key, 1, IPC_CREAT);//獲取信號(hào)量struct sembuf sops;sops.sem_num = 0;sops.sem_op = -1;sops.sem_flg = SEM_UNDO;semop(semid, &sops, 1);//拷貝文件system("cp product.txt ship.txt"); }?
轉(zhuǎn)載于:https://www.cnblogs.com/d442130165/p/5225409.html
總結(jié)
以上是生活随笔為你收集整理的[国嵌攻略][084][信号同步编程]的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Activity(二)
- 下一篇: 耦合度和聚合度