ipc 进程间的系统 V 通信system v : 共享内存 信号量集
IPC对象操作通用框架:
0x ftok
key值 ==> 申请 ==》读写 ==》关闭 ==》卸载
key值:===》唯一键值
ftok(), shmget() shmat() ,shmdt(),shmctl()
模拟进程间等待通信,首先读端先运行,然后使用将自己的id先传过去pause函数暂停,写程序后运行,在写程序运行起来之后通过kill 发信号将读程序释放就行了。
//读
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <signal.h>
void handle(int num)
{
}
//定义信号函数,使用没有具体含义的用户一信号
signal(SIGUSR1,handle);
key_t key = ftok("/etc/passwd", '!');
if(-1 == key)
{
perror("ftok");
exit(1);
}
int shmid = shmget(key, 4096, IPC_CREAT|0666);
if(-1 == shmid)
{
perror("shmget");
exit(1);
}
char * temp = shmat(shmid, NULL, !SHM_RDONLY);
if((void *)-1 == temp)
{
perror("shmat");
exit(1);
}
pid_t pid = getpid();
memcpy(temp, &pid, 4);
printf("%d\n", pid);
pause();
printf("rec: %s\n", temp);
shmdt(temp);
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
//写
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <signal.h>
int main(int argc, const char *argv[])
{
key_t key = ftok("/etc/passwd", ‘!’);
if(-1 == key)
{
perror(“ftok”);
exit(1);
}
int shmid = shmget(key, 4096, IPC_CREAT|0666);
if(-1 == shmid)
{
perror(“shmget”);
exit(1);
}
char * temp = shmat(shmid, NULL, !SHM_RDONLY);
if((void *)-1 == temp)
{
perror(“shmat”);
exit(1);
}
pid_t pid;
//使用memcpy 拷贝内存
memcpy(&pid, temp, 4); //pid 四个字节
printf("%u\n", pid);
//此处发信号给另外进程。
kill(pid, SIGUSR1);
strcpy(temp, “nihao”);
printf(“fa: %d\n”, sizeof(“hello”));
shmdt(temp);
return 0;
}
本文深入探讨了Linux环境下进程间通信(IPC)的系统V通信机制,包括共享内存和信号量集的使用。通过示例代码,详细展示了如何利用ftok、shmget等函数创建、读写和管理共享内存段,以及如何通过信号量协调进程间的访问冲突。
1872

被折叠的 条评论
为什么被折叠?



