主要运用了进程创建 mmap映射区 等知识点
#include<stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/wait.h>
int main(){
int new_fd,old_fd,i;
long int size;
char *p_old, *p_new;
pid_t pid;
old_fd = open("src.txt", O_RDWR,0644);//源文件 自己设定
if (old_fd < 0){
perror("open error\n");
exit(1);
}
size = lseek(old_fd, 0, SEEK_END);
p_old = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, old_fd, 0);
//
new_fd = open("result", O_RDWR | O_CREAT | O_TRUNC, 0644);
if (new_fd < 0){
perror("open error\n");
exit(1);
}
ftruncate(new_fd, size);
p_new = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, new_fd, 0);
/
size = lseek(old_fd, 0, SEEK_END);
long int cut = size / 5;//进程为5
long int yu = size % 5;//
for(i=0; i<5; i++){
pid = fork();
if(pid == 0)
break;
}
if(i<=3){
printf("pid = %d\n", getpid());
memcpy(p_new+i*cut,p_old+i*cut,cut);
}else if(i==4){
printf("pid = %d\n", getpid());
memcpy(p_new+i*cut,p_old+i*cut,cut+yu);
}else{
int j;
pid_t pid2;
for(j=0; j<5;j++){
while((pid2=waitpid(-1, NULL,WNOHANG)) == 0 && pid2 != -1);
printf("---pid2=%d\n", pid2);
}
}
return 0;
}