linux共享内存与信号量的使用
生活随笔
收集整理的這篇文章主要介紹了
linux共享内存与信号量的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1、使用共享內存在兩個進程中傳值
2、使用信號量做同步控制。
#include <unistd.h> #include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h>static int init_semvalue (int); static void del_semvalue (int); static int P (int); static int V (int);//自己定義的semun結構體 union semun {int val;struct semid_ds *buf;unsigned short *array;struct seminfo *__buf; };int main (int argc, char *argv[]) {int var_cri = 0;int sem_id;pid_t pid;int *num;//創建一個信號量sem_id = semget ((key_t) 2234, 1, 0666 | IPC_CREAT);//初始化一個信號量if (!init_semvalue (sem_id)){fprintf (stderr, "Failed to initialize semaphore!\n");exit (EXIT_FAILURE);}//創建子進程if ((pid = fork ()) == 0) //子進程{int shid=shmget((key_t)654321,(size_t)4, 0600|IPC_CREAT);if(shid==-1){perror("shmget");exit(EXIT_FAILURE);}num=shmat(shid, NULL,0);if(num==NULL){perror("shmat");exit(EXIT_FAILURE);}while (1){//臨界區if (!P (sem_id))//申請資源exit (EXIT_FAILURE);int i;for (i = 0; i != 10; ++i){(*num)++;printf ("[child]: %d:%d\n", i,*num);sleep (1);}if (!V (sem_id))//釋放資源exit (EXIT_FAILURE);}}else if (pid > 0) //父進程{int shid=shmget((key_t)654321,(size_t)4, 0600|IPC_CREAT);if(shid==-1){perror("shmget");exit(EXIT_FAILURE);}num=shmat(shid, NULL,0);if(num==NULL){perror("shmat");exit(EXIT_FAILURE);}sleep (1);while (1){//臨界區if (!P (sem_id))exit (EXIT_FAILURE);int i;for (i = 0; i != 10; ++i){(*num)++;printf ("[parent]: %d:%d\n", i,*num);sleep (1);}if (!V (sem_id))exit (EXIT_FAILURE);}sleep (8);//銷毀信號量del_semvalue (sem_id);}exit (EXIT_SUCCESS); }static int init_semvalue (int id) {union semun sem_union;sem_union.val = 1;if (semctl (id, 0, SETVAL, sem_union) == -1)//設置信號量集中的信號量值valuereturn (0);return (1); }static void del_semvalue (int id) {union semun sem_union;if (semctl (id, 0, IPC_RMID, sem_union) == -1)//IPC——RMID將信號量集從內存中刪除fprintf (stderr, "Failed to delete semaphore\n"); }int P (int id) {struct sembuf op;op.sem_num = 0;//單信號op.sem_op = -1;//P操作op.sem_flg = 0;if (semop (id, &op, 1) < 0)//改變key,它代表進程要使用的某個資源return 0;return 1; }int V (int id) {struct sembuf op;op.sem_num = 0;op.sem_op = 1;//V操作op.sem_flg = 0;if (semop (id, &op, 1) < 0)return 0;return 1; }總結
以上是生活随笔為你收集整理的linux共享内存与信号量的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Vimium插件让键盘党像操作Vim一样
- 下一篇: 北漂两年来的思考