举几个C代码中使用shmsrc的例子
时间: 2023-06-20 20:04:28 浏览: 120
1. 下面是一个生产者和消费者使用共享内存进行通信的例子,其中使用了shmsrc来获取共享内存的数据:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main()
{
key_t key = ftok(".", 's');
int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
char *shmaddr = (char *) shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
char buf[SHM_SIZE];
while (1) {
// 生产者向共享内存写入数据
printf("Enter a message: ");
fgets(buf, SHM_SIZE, stdin);
strncpy(shmaddr, buf, SHM_SIZE);
// 消费者从共享内存读取数据
printf("Received: %s", shmaddr);
}
if (shmdt(shmaddr) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}
if (shmctl(shmid, IPC_RMID, 0) == -1) {
perror("shmctl");
exit(EXIT_FAILURE);
}
return 0;
}
```
2. 下面是一个父进程和子进程之间使用共享内存进行通信的例子,其中使用了shmsrc来获取共享内存的数据:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main()
{
key_t key = ftok(".", 's');
int shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget");
exit(EXIT_FAILURE);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
char *shmaddr = (char *) shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
printf("Child process: %s", shmaddr);
if (shmdt(shmaddr) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
} else {
char *shmaddr = (char *) shmat(shmid, NULL, 0);
if (shmaddr == (char *) -1) {
perror("shmat");
exit(EXIT_FAILURE);
}
char buf[SHM_SIZE];
printf("Enter a message: ");
fgets(buf, SHM_SIZE, stdin);
strncpy(shmaddr, buf, SHM_SIZE);
if (shmdt(shmaddr) == -1) {
perror("shmdt");
exit(EXIT_FAILURE);
}
wait(NULL);
if (shmctl(shmid, IPC_RMID, 0) == -1) {
perror("shmctl");
exit(EXIT_FAILURE);
}
return 0;
}
}
```
阅读全文