进程间通信
最编程
2024-08-02 09:40:26
...
shmctl.c
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#define ASSERT(res) if((res)<0){perror(__FUNCTION__);exit(-1);}
// 打印 ipc_perm
void printPerm(struct ipc_perm *perm) {
printf("euid of owner = %d\n", perm->uid);
printf("egid of owner = %d\n", perm->gid);
printf("euid of creator = %d\n", perm->cuid);
printf("egid of creator = %d\n", perm->cgid);
printf("mode = 0%o\n", perm->mode);
}
// 打印 ipc 内核对象信息
void printShmid(struct shmid_ds *shmid) {
printPerm(&shmid->shm_perm);
printf("segment size = %ld\n", shmid->shm_segsz);
printf("last attach time = %s", ctime(&shmid->shm_atime));
printf("last detach time = %s", ctime(&shmid->shm_dtime));
printf("last change time = %s", ctime(&shmid->shm_ctime));
printf("pid of creator = %d\n", shmid->shm_cpid);
printf("pid of last shmat/shmdt = %d\n", shmid->shm_lpid);
printf("No. of current attaches = %ld\n", shmid->shm_nattch);
}
// 创建 ipc 内核对象
void create() {
int id = shmget(0x8888, 123, IPC_CREAT | IPC_EXCL | 0664);
printf("create %d\n", id);
ASSERT(id);
}
// IPC_STAT 命令使用,用来获取 ipc 内核对象信息
void show() {
int id = shmget(0x8888, 0, 0);
ASSERT(id);
struct shmid_ds shmid;
ASSERT(shmctl(id, IPC_STAT, &shmid));
printShmid(&shmid);
}
// IPC_SET 命令使用,用来设置 ipc 内核对象信息
void set() {
int id = shmget(0x8888, 123, IPC_CREAT | 0664);
ASSERT(id);
struct shmid_ds shmid;
ASSERT(shmctl(id, IPC_STAT, &shmid));
shmid.shm_perm.mode = 0600;
ASSERT(shmctl(id, IPC_SET, &shmid));
printf("set %d\n", id);
}
// IPC_RMID 命令使用,用来删除 ipc 内核对象
void rm() {
int id = shmget(0x8888, 123, IPC_CREAT | 0664);
ASSERT(id);
ASSERT(shmctl(id, IPC_RMID, NULL));
printf("remove %d\n", id);
}
// 挂接和卸载
void at_dt() {
int id = shmget(0x8888, 123, IPC_CREAT | 0664);
ASSERT(id);
char *buf = shmat(id, NULL, 0);
if (buf == (char*)-1) ASSERT(-1);
printf("shmat %p\n", buf);
sleep(5); // 等待 5 秒后,执行 shmdt
ASSERT(shmdt(buf));
printf("shmdt %p\n", buf);
}
int main(int argc, char *argv[]) {
if (argc < 2) {
printf("usage: %s <option -c -v -s -d -a>\n", argv[0]);
return -1;
}
printf("I'm %d\n", getpid());
if (!strcmp(argv[1], "-c")) {
create();
}
else if (!strcmp(argv[1], "-v")) {
show();
}
else if (!strcmp(argv[1], "-s")) {
set();
}
else if (!strcmp(argv[1], "-d")) {
rm();
}
else if (!strcmp(argv[1], "-a")) {
at_dt();
}
return 0;
}
上一篇: 8款实现进程间通讯的方式
下一篇: 进程之间的通信
推荐阅读
-
STM32 I2C 通信协议详解
-
等待缓存锁:无法获取/var/lib/dpkg/lock-frontend。锁被进程 5427(unattended-upgr)持有。
-
[Linux] 逐层了解文件系统 (1) - 操作文件的进程
-
K8s 的两个节点间通信案例
-
[Linux 进程概念
-
I\O 进程线程(第27天)
-
Linux 流程控制 - II.进程替换
-
交通目标识别数据集 YOLO 模型 ui 界面 ✓ 图像数量 15,000 张,包括 xml 和 txt 标记 11 个类别 交通道路车辆行人 红黄绿数据集 交通灯数据集 交通信号数据集
-
英伟达™(NVIDIA®)GPGPU 通信架构解析
-
STM32 微控制器_(HAL 库]6-3 [串行通信 UART、USART] 串行通信发送/接收字符