C语言共享内存互斥量demon
时间: 2023-08-26 10:06:51 浏览: 50
以下是一个简单的 C 语言程序,它使用了共享内存和互斥量来实现进程间的通信和同步:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <pthread.h>
#define SHM_SIZE 1024
struct shared_memory {
int counter;
};
int main()
{
int shmid;
struct shared_memory *shm;
pthread_mutex_t *mutex;
// 创建共享内存
shmid = shmget(IPC_PRIVATE, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
exit(1);
}
// 将共享内存附加到当前进程
shm = (struct shared_memory *) shmat(shmid, NULL, 0);
if (shm == (struct shared_memory *) -1) {
perror("shmat");
exit(1);
}
// 初始化共享内存
shm->counter = 0;
// 创建互斥量
mutex = (pthread_mutex_t *) shmat(shmid, NULL, 0);
if (mutex == (pthread_mutex_t *) -1) {
perror("shmat");
exit(1);
}
pthread_mutex_init(mutex, NULL);
// 创建子进程
pid_t pid = fork();
if (pid < 0) {
perror("fork");
exit(1);
} else if (pid == 0) {
// 子进程
int i;
for (i = 0; i < 10; i++) {
// 加锁
pthread_mutex_lock(mutex);
// 计数器加一
shm->counter++;
// 解锁
pthread_mutex_unlock(mutex);
sleep(1);
}
} else {
// 父进程
int i;
for (i = 0; i < 10; i++) {
// 加锁
pthread_mutex_lock(mutex);
// 计数器加一
shm->counter++;
// 解锁
pthread_mutex_unlock(mutex);
sleep(1);
}
}
// 销毁互斥量
pthread_mutex_destroy(mutex);
// 将共享内存从当前进程中分离
shmdt(shm);
shmdt(mutex);
// 删除共享内存
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
```
这个程序使用了 `shmget` 函数来创建共享内存,`shmat` 函数将共享内存附加到当前进程,`pthread_mutex_init` 函数创建互斥量。子进程和父进程都会对共享内存中的计数器进行 10 次加一操作,每次加一之前需要先使用互斥量进行加锁,加一完成后再解锁。最后,使用 `pthread_mutex_destroy` 函数销毁互斥量,并使用 `shmdt` 函数将共享内存从当前进程中分离,最终使用 `shmctl` 函数删除共享内存。
注意:在使用共享内存和互斥量时,需要注意避免死锁和竞态条件等问题。建议在使用时仔细阅读相关文档和示例程序,以确保程序的正确性和稳定性。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)