共享内存在两个不相干的程序之间的通讯

//创建
#include <stdio.h>

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <signal.h>

int main(int argc, char *argv[])
{
	setbuf(stdout,NULL);
	int shmid;
	char *viraddr;

	shmid = shmget(1234, 100, 0666| IPC_CREAT);
	viraddr = (char *)shmat(shmid,0,0);

	int times = 0;
	memcpy(viraddr, "hello", 100);

	printf("shmid=%d\n", shmid);
	while(1)
	{
		sprintf(viraddr + 5, "%d", times++);
	    printf("buf=%s\n", viraddr);
	    if(times == 10000)
	    	break;
	    sleep(3);
	}

	shmdt(viraddr);          /*断开附接*/
	return 0;

}

//接收
#include <stdio.h>

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/wait.h>
#include <signal.h>

int main(int argc, char *argv[])
{
	int shmid;
	char *viraddr;

	shmid = shmget(1234,100,0666|IPC_CREAT);
	viraddr = (char *)shmat(shmid, 0, 0);

	while(1)
	{
		printf("this is recv = %s\n", viraddr);
		sleep(3);
	}
    shmdt(viraddr);                  /*断开连接*/
    shmctl(shmid,IPC_RMID,0);                /*撤销共享内存*/

	return 0;
}



 
 

猜你喜欢

转载自blog.csdn.net/destiny_chen/article/details/78971479
今日推荐