linux 信号量的例程
时间: 2023-06-08 15:07:28 浏览: 123
linux信号量实例代码
5星 · 资源好评率100%
这是一个使用信号量的 Linux C 语言程序:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/sem.h>
int main(int argc, char const *argv[])
{
int semid;
// 创建一个包含 1 个信号量的集合
semid = semget(IPC_PRIVATE, 1, 0666);
if (semid == -1) {
perror("semget");
exit(EXIT_FAILURE);
}
// 初始化信号量的值为 1
if (semctl(semid, 0, SETVAL, 1) == -1) {
perror("semctl");
exit(EXIT_FAILURE);
}
// 创建一个子进程
if (fork() == 0) {
struct sembuf sops;
// 子进程等待信号量
sops.sem_num = 0;
sops.sem_op = -1;
sops.sem_flg = 0;
if (semop(semid, &sops, 1) == -1) {
perror("semop");
exit(EXIT_FAILURE);
}
printf("Child process is working\n");
// 子进程增加信号量的值
sops.sem_num = 0;
sops.sem_op = 1;
sops.sem_flg = 0;
if (semop(semid, &sops, 1) == -1) {
perror("semop");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
} else {
struct sembuf sops;
// 父进程等待信号量
sops.sem_num = 0;
sops.sem_op = -1;
sops.sem_flg = 0;
if (semop(semid, &sops, 1) == -1) {
perror("semop");
exit(EXIT_FAILURE);
}
printf("Parent process is working\n");
// 父进程增加信号量的值
sops.sem_num = 0;
sops.sem_op = 1;
sops.sem_flg = 0;
if (semop(semid, &sops, 1) == -1) {
perror("semop");
exit(EXIT_FAILURE);
}
// 销毁信号量
if (semctl(semid, 0, IPC_RMID, 0) == -1) {
perror("semctl");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
return 0;
}
```
这个程序创建一个包含 1 个信号量的集合,初始化信号量的值为 1,然后创建一个子进程。子进程等待信号量,然后输出一条信息,最后增加信号量的值。父进程也等待信号量,输出一条信息,然后增加信号量的值。最后销毁信号量。运行程序可以看到以下输出:
```
Parent process is working
Child process is working
```
阅读全文