Linux中信号量的示例分析

2023-04-12 08:32:00 分析 示例 信号量

信号量是一个计数器,用于跟踪资源的使用情况。如果资源可用,则信号量的值为正,如果资源不可用,则信号量的值为负。当一个进程试图获取一个资源时,它会使用信号量来检查资源的可用性。如果资源可用,则信号量的值会减少,如果资源不可用,则信号量的值会增加。

信号量有两种类型:互斥信号量和计数信号量。互斥信号量用于保护共享资源,确保每次只有一个进程可以访问该资源。计数信号量用于跟踪可用资源的数量,允许多个进程访问可用资源。

下面是一个使用信号量的示例程序:

#include #include #include #include #include #include #define KEY 0x1234 int main() { int semid, pid, ret; semid = semget(KEY, 1, IPC_CREAT | 0666); if (semid < 0) { perror("semget"); exit(1); } ret = semctl(semid, 0, SETVAL, 1); if (ret < 0) { perror("semctl"); exit(1); } pid = fork(); if (pid < 0) { perror("fork"); exit(1); } if (pid == 0) { // child process printf("Child process trying to acquire resource

"); struct sembuf sb; sb.sem_num = 0; sb.sem_op = -1; // try to acquire the resource sb.sem_flg = SEM_UNDO; ret = semop(semid, &sb, 1); if (ret < 0) { perror("semop"); exit(1); } printf("Child process acquired resource

"); sleep(5); printf("Child process releasing resource

"); sb.sem_num = 0; sb.sem_op = 1; // release the resource sb.sem_flg = SEM_UNDO; ret = semop(semid, &sb, 1); if (ret < 0) { perror("semop"); exit(1); } printf("Child process released resource

"); } else { // parent process printf("Parent process trying to acquire resource

"); struct sembuf sb; sb.sem_num = 0; sb.sem_op = -1; // try to acquire the resource sb.sem_flg = SEM_UNDO; ret = semop(semid, &sb, 1); if (ret < 0) { perror("semop"); exit(1); } printf("Parent process acquired resource

"); sleep(5); printf("Parent process releasing resource

"); sb.sem_num = 0; sb.sem_op = 1; // release the resource sb.sem_flg = SEM_UNDO; ret = semop(semid, &sb, 1); if (ret < 0) { perror("semop"); exit(1); } printf("Parent process released resource

"); } return 0; }

程序的输出如下所示:

Parent process trying to acquire resource Parent process acquired resource Child process trying to acquire resource Child process acquired resource Parent process releasing resource Child process releasing resource

从输出可以看出,当父进程试图获取资源时,子进程会等待,直到父进程释放资源。

相关文章