1. 程式人生 > >使用共享記憶體實現Linux程序通訊

使用共享記憶體實現Linux程序通訊

我們通過共享記憶體的技術實現程序間的通訊,剛開始定義兩個檔案,讀程序從輸入檔案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");
}