使用C语言写一个进程间通信的程序,使用共享内存
时间: 2024-05-07 13:17:58 浏览: 12
好的,我可以为您编写一个使用共享内存实现进程间通信的C程序。以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#define SHM_SIZE 1024
int main() {
int shmid;
key_t key;
char *shm, *s;
// 创建共享内存段
key = ftok(".", 's');
shmid = shmget(key, SHM_SIZE, IPC_CREAT | 0666);
if (shmid < 0) {
perror("shmget");
exit(1);
}
// 将共享内存段附加到进程的地址空间
shm = shmat(shmid, NULL, 0);
if (shm == (char *) -1) {
perror("shmat");
exit(1);
}
// 在共享内存段中写入数据
s = shm;
for (char c = 'a'; c <= 'z'; c++) {
*s++ = c;
}
*s = '\0';
// 分离共享内存段
shmdt(shm);
// 读取共享内存段中的数据
shm = shmat(shmid, NULL, 0);
if (shm == (char *) -1) {
perror("shmat");
exit(1);
}
printf("%s\n", shm);
// 分离共享内存段
shmdt(shm);
// 删除共享内存段
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
```
这个程序创建一个共享内存段,然后在其中写入字母a到z,最后再从共享内存段中读取数据并输出。运行这个程序,你会看到输出结果为“abcdefghijklmnopqrstuvwxyz”。
当然,这只是一个简单的示例。在实际的应用中,你需要根据自己的需求修改代码。