// 、、使用内存映射可以拷贝文件
/*
对原始文件进行内存映射
创建一个新文件
把新文件的数据拷贝映射到内存中
通过内存拷贝将第一个文件的内存映射区拷贝到第二个文件的内存映射区
释放资源
*/
// 匿名映射,不需要文件实体来进行内存映射
// 只能用于有血缘关系的进程间通信
#include <sys/mman.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
/*
// kill函数
// pid》0将信号发送给指定进程
// =0:将信号发送给当前进程组
// =-1:将信号发送给每一个有权限接受这个信号的进程
// 《-1:进程组id的绝对值
// sig,要发送的信号
// kill(getppid(), 9);
// kill(getpid(), 9);
// raise函数,给当前进程发送信号
// sig,要发送的信号,成功返回0,失败返回非0*/
pid_t pid = fork();
if(pid==0){
for(int i=0;i<5;i++) {
printf("孩子进程%d\n", i);
sleep(1);
}
}else if(pid>0) {
printf("爹进程\n");
sleep(2);
printf("傻儿子\n");
kill(pid,SIGINT);
}
return 0;}
/*
// char * buf;
// strcpy(buf, "cao nima");return 0;}/*
// 修改mmap的flags参数,之前使用的是MAP_SHARED
// 现在我们要用的是MAP_ANON
int len = 1204;
void *ptr = mmap(NULL, len, PROT_READ|PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0);
if (ptr == MAP_FAILED)
{
perror("mmap");
exit(0);
}
// 父子进程间通信
int pid = fork();
if (pid > 0)
{
strcpy((char *)ptr, "hello world");
wait(NULL);
}
else if (0 == pid)
{
sleep(1);
printf("%s\n", (char *)ptr);
}
// 释放内存映射区
int ret = munmap(ptr, len);
// int fd = open("englsih.txt", O_RDONLY);
// // 获取原始文件的大小
// int len = lseek(fd, 0, SEEK_END);
// // 创建一个新文件,并对其大小进行拓展
// int fd1 = open("cpy.txt", O_CREAT | O_RDWR, 0664);
// truncate("cpy.txt", len);
// write(fd1, " ", 1);
// // 分别进行内存映射
// void *ptr = mmap(NULL, len, PROT_READ, MAP_SHARED, fd, 0);
// void *ptr1 = mmap(NULL, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd1, 0);
// if (ptr == MAP_FAILED)
// {
// perror("mmap");
// exit(0);
// }
// if (ptr1 == MAP_FAILED)
// {
// perror("mmap");
// exit(0);
// }
// // 内存拷贝
// memcpy(ptr1, ptr, len);
// munmap(ptr1, len);
// munmap(ptr, len);
// close(fd1);
// close(fd);
return 0;
}
*/
父进程调用kill函数,给子进程发送SIGINT
信号来终止子进程