黑马《linux系统编程》学习笔记(从46到50)

四十六. 没有血缘关系的进程间通信_mmap

mmap_r_ipc.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>


int main(int argc, const char* argv[])
{
	
	int fd = open("temp",O_RDWR | O_CREAT, 0664);
	fruncate(fd,4096);
	
	int len = lseek(fd,0,SEEK_END);
	
    //创建匿名内存映射区
    void * ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if(ptr == MAP_FAILED)
    {
        perror("mmap error");
        exit(1);
    }

	while(1)
	{
		sleep(1);
		printf("%s\n",(char*)ptr + 1024);

	}
		

	//释放
    int ret = munmap(ptr, len);
    if(ret == -1)
    {
        perror("munmap error");
        exit(1);
    }

    return 0;
}

mmap_w_ipc.c

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <string.h>
#include <sys/mman.h>
#include <fcntl.h>


int main(int argc, const char* argv[])
{
	
	int fd = open("temp",O_RDWR | O_CREAT, 0664);
	//创建匿名内存映射区
	int len = 4096;
	//注意这里的参数的变化,
    void * ptr = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if(ptr == MAP_FAILED)
    {
        perror("mmap error");
        exit(1);
    }

	while(1)
	{
		char* p = (char*)ptr;
		p += 1024;
		strcpy(p,"hello parent, i am your friend!!\n");
		sleep(2);
	}
		

	//释放
    int ret = munmap(ptr, len);
    if(ret == -1)
    {
        perror("munmap error");
        exit(1);
    }

    return 0;
}

四十七. 信号知识点概述

 四十八. 管道复习

四十九. 信号的介绍

五十. 阻塞信号集和未解信号集的概念

猜你喜欢

转载自blog.csdn.net/garrulousabyss/article/details/85333498