本文主要是介绍linuxIPC之共享内存,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
生产者
/*************************************************************************> File Name: productor.c> Author: XXDK> Email: v.manstein@qq.com > Created Time: Sun 19 Mar 2017 10:57:29 PM PDT************************************************************************/#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<signal.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<errno.h>typedef struct mesg {pid_t pid;char buf[1024];
}msg_t;void handler(int signo)
{return;
}
int main()
{int shmid;key_t key;pid_t cpid;msg_t* msgp;key = ftok("./test", 100);shmid = shmget(key, 1024, IPC_CREAT|IPC_EXCL|0666);if(shmid == -1) {if(errno == EEXIST) {shmid = shmget(key, 0, 0);} else {perror("shmget error");exit(-1);}}if((msgp = (msg_t*)shmat(shmid, NULL, 0)) == (msg_t*)-1) {perror("shmat error");exit(-1);}signal(SIGUSR1, handler);// 从共享内存中读取消费者的pidcpid = msgp->pid;// 将生产者的pid放入共享内存msgp->pid = getpid();// 通知消费者kill(cpid, SIGUSR1);// 挂起等待消费者解析pid, 由消费者解析完成的// 信号来唤醒pause();printf("linked %d ok\n", cpid);while(1) {printf("input: ");fflush(stdout);fgets(msgp->buf, sizeof(msgp->buf), stdin);if(strncmp(msgp->buf, "quit", 4) == 0) {kill(cpid, SIGKILL);break;}// 通知数据装载完毕kill(cpid, SIGUSR1);// 挂起等待消费者解析数据, 由消费者解析完成的// 信号来唤醒pause();}return 0;
}

/*************************************************************************> File Name: consumer.c> Author: XXDK> Email: v.manstein@qq.com > Created Time: Sun 19 Mar 2017 10:57:29 PM PDT************************************************************************/#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#include<signal.h>
#include<fcntl.h>
#include<sys/stat.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<errno.h>typedef struct mesg {pid_t pid;char buf[1024];
}msg_t;void handler(int signo)
{return;
}
int main()
{int shmid;key_t key;pid_t ppid;msg_t* msgp;key = ftok("./test", 100);shmid = shmget(key, 1024, IPC_CREAT|IPC_EXCL|0666);if(shmid == -1) {if(errno == EEXIST) {shmid = shmget(key, 0, 0);} else {perror("shmget error");exit(-1);}}if((msgp = (msg_t*)shmat(shmid, NULL, 0)) == (msg_t*)-1) {perror("shmat error");exit(-1);}signal(SIGUSR1, handler);// 写入自己的pid到共享内存msgp->pid = getpid();// 等待生产者解析我的pid,并在解析完成后唤醒我pause();// 读取生产者的pidppid = msgp->pid;printf("linked %d ok\n", ppid);while(1) {fputs(msgp->buf, stdout);kill(ppid, SIGUSR1);pause();}return 0;
}
这篇关于linuxIPC之共享内存的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!