在linux中实现共享内存方式的进程间通信
上面代码都在
linux:Ubuntu12.04
gcc:4.6.3 上运行通过。
分别有两个程序运行read.c和write.c
write.c从终端输入到全局定义的结构体shm_t的buf[]数组中
read.c从buf[]中读取并输出、打印
下面为read.c文件
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<errno.h>
#include<unistd.h>
#include<signal.h>//包含的头文件
#include<string.h>
//利用共享内存进行进程间的通信
typedef struct{
pid_t pid;
char buf[100];//定义的结构体
}shm_t;
void fun(int signum)
{
//空操作
}
int main(int argc, const char *argv[])
{
key_t key;
int shmid;
pid_t pid;
shm_t *p;
//recive the signal from the write
//then turn to pause()
signal(SIGUSR1,fun);
//init the shmid memory
key = ftok(".",'a');//key_t ftok(const char *pathname, int proj_id)
define the key value
if((shmid = shmget(key,100,0664 | IPC_CREAT | IPC_EXCL)) == -1){
if(errno == EEXIST){
shmid = shmget(key,100,0664); //int shmget(key_t key, size_t size, int shmflg);
//shmflag follows IPC_CREAT IPC_EXCL
p = (shm_t *)shmat(shmid,NULL,0);//有必要进行强转,在我运行时不强转会出问题
//the purpose of this step send
//the pid of process
pid = p->pid;
p->pid = getpid();//get the current pidnum
kill(pid,SIGUSR1);//send signal to write
}
else{
perror("shget");
exit(1);
}
}
//当shimd不存在,首次执行时
else{
p = (shm_t *)shmat(shmid,NULL,0);
p->pid = getpid();
pause();//wait for signal from write
pid = p->pid;//change the struct's pid number
}
while(1){
//程序阻塞在这里等待write发送信号
pause();
//when enter the quit,will quit from the progress
if(strncmp(p->buf,"quit",4) == 0){
break;//breakout the while(1)
}
printf("buf is %s",p->buf);
//send signal the write
kill(pid,SIGUSR1);
}
//destroy the shmid
shmdt(p);
shmctl(shmid,IPC_RMID,NULL);
return 0;
}
接下来是write.c文件,用于向共享内存进行写内容
**#include<>;;;has the same headfiles as read.c has**
int main(int argc, const char *argv[])
{
key_t key;
shm_t *p;
int shmid;
pid_t pid;
signal(SIGUSR1,fun);
//same function as read do
//init the
key = ftok(".",'a');
if((shmid = shmget(key,sizeof(shm_t),0664 | IPC_CREAT|IPC_EXCL)) == -1){
if(errno == EEXIST){
shmid = shmget(key,100,0664);
p = (shm_t *)shmat(shmid,NULL,0);
pid = p->pid;
p->pid = getpid();
kill(pid,SIGUSR1);
}
else{
perror("shmget");
exit(1);
}
}
else{
p = (shm_t *)shmat(shmid,NULL,0);
p->pid = getpid();
pause();
pid = p->pid;
}
while(1){
//read the charaters from terminal
fgets(p->buf,100,stdin);
kill(pid,SIGUSR1);//send the signal to read
if(strncmp(p->buf,"quit",4) == 0)
break;//breakout while()
pause();//wait the signal from read
}
return 0;
}
进程间通信的方式有很多,管道:有名管道、无名管道 ,信号,共享内存,消息队列,信号灯等,还有套接字,会在网络编程里出现比较多。