版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/baidu_38304645/article/details/82823938
我们通过共享内存的技术实现进程间的通信,刚开始定义两个文件,读进程从输入文件intput中读取数据,并将其放入共享内存中,然后写进程将共享内存中的数据输出到输出文件output中。程序比较简单,因此只能实现5个字符的通信。待以后再改进吧。
读进程:
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
key_t key;
key = 1234;
int shm_id = shmget(key, 27, IPC_CREAT|0666);
if(shm_id == -1)
{
perror("shmget error");
return;
}
FILE *fp = fopen("input", "r");
if(fp == NULL)
{
perror("Open file recfile");
exit(1);
}
char *s = shmat(shm_id, NULL, 0);
fread(s, sizeof(char), 5, fp );
fclose(fp);
if(shmdt(s)==-1)
perror("detach error");
}
写进程:
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
key_t key;
key = 1234;
int shm_id;
shm_id = shmget(key, 27, IPC_CREAT|0666);
if(shm_id == -1)
{
perror("shmget error");
return;
}
char *s = shmat(shm_id, NULL, 0);
FILE *fp = fopen("output", "w");
if(fp == NULL)
{
perror("Open file recfile");
exit(1);
}
fwrite(s, sizeof(char), 5, fp);
fclose(fp);
if(shmdt(s)==-1)
perror("detach error");
}