帮忙使用C语言封装函数,使用互斥量和共享内存进行进程间通信
时间: 2024-05-15 07:12:59 浏览: 106
好的,下面是一个简单的示例代码,它演示了如何使用互斥量和共享内存进行进程间通信,具体实现方式如下:
1. 定义共享内存结构体
```c
typedef struct {
int value;
} shared_data_t;
```
2. 创建共享内存
```c
int fd = shm_open("/myshm", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd < 0) {
perror("shm_open");
exit(1);
}
if (ftruncate(fd, sizeof(shared_data_t)) == -1) {
perror("ftruncate");
exit(1);
}
```
3. 映射共享内存到进程地址空间
```c
shared_data_t *shared_data = mmap(NULL, sizeof(shared_data_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (shared_data == MAP_FAILED) {
perror("mmap");
exit(1);
}
```
4. 初始化互斥量
```c
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_t *mutex = (pthread_mutex_t*)mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
pthread_mutex_init(mutex, &attr);
pthread_mutexattr_destroy(&attr);
```
5. 在父子进程中使用共享内存和互斥量进行通信
```c
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
} else if (pid == 0) {
// 子进程
pthread_mutex_lock(mutex);
shared_data->value = 100;
pthread_mutex_unlock(mutex);
} else {
// 父进程
pthread_mutex_lock(mutex);
printf("shared_data->value = %d\n", shared_data->value);
pthread_mutex_unlock(mutex);
}
```
完整代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <pthread.h>
#include <sys/wait.h>
typedef struct {
int value;
} shared_data_t;
int main() {
int fd = shm_open("/myshm", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
if (fd < 0) {
perror("shm_open");
exit(1);
}
if (ftruncate(fd, sizeof(shared_data_t)) == -1) {
perror("ftruncate");
exit(1);
}
shared_data_t *shared_data = mmap(NULL, sizeof(shared_data_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (shared_data == MAP_FAILED) {
perror("mmap");
exit(1);
}
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED);
pthread_mutex_t *mutex = (pthread_mutex_t*)mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, -1, 0);
pthread_mutex_init(mutex, &attr);
pthread_mutexattr_destroy(&attr);
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
} else if (pid == 0) {
// 子进程
pthread_mutex_lock(mutex);
shared_data->value = 100;
pthread_mutex_unlock(mutex);
} else {
// 父进程
pthread_mutex_lock(mutex);
printf("shared_data->value = %d\n", shared_data->value);
pthread_mutex_unlock(mutex);
}
wait(NULL);
pthread_mutex_destroy(mutex);
munmap(mutex, sizeof(pthread_mutex_t));
munmap(shared_data, sizeof(shared_data_t));
shm_unlink("/myshm");
return 0;
}
```
希望对你有所帮助!
阅读全文