Home > Back-end >  Mmap includes multi-process copy files
Mmap includes multi-process copy files

Time:11-18

//by mmap multi-process copy files 
//
//
#include
#include
#include
#include
#include
#include
#include
#include


using namespace std;

Int main (int arg c, char * argv [])
{
If (arg c!
=2){
Cout & lt; <"./03 _homework_mutiprocess_copy filename "& lt; return -1;
}

//the first open source file and get the file size, the size of the distribution of each process according to the three process copy
Int fd_sor=open (argv [1], O_RDONLY);
Off_t filesize=lseek (fd_sor, 0, SEEK_END);
Lseek (fd_sor, 0, SEEK_SET);
Int wrsize=filesize/3;//wrsize is the size of the process of the first three copy
Int tlsize=filesize % wrsize;//tlsize is the size of the fourth tail process copy


//open the target file and expand in line with the source file size
Char tar_buf [64]={0};
Sprintf (tar_buf, copy_ "% s", argv [1]).
Int fd_tar=open (tar_buf, O_RDWR | O_CREAT | O_TRUNC, 0666);
//modify the file size is consistent with the copy files
Ftruncate (fd_tar filesize);

//the main process to create two file mapping
Char * sor_p=(char *) mmap (NULL, filesize, PROT_READ MAP_SHARED, fd_sor, 0).
If (sor_p==MAP_FAILED)
{
Cout & lt; <"Sor mmap err!" The return - 2;
}
Close (fd_sor);

Char * tar_p=(char *) mmap (NULL, filesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd_tar, 0).
If (tar_p==MAP_FAILED)
{
Cout & lt; <"Tar mmap err!" The return - 3;
}
Close (fd_tar);

Char * temp_tar=tar_p;
Char * temp_sor=sor_p;

Int id;

For (id=0; Id & lt; 4. Id + +)
{
pid_t pid=fork();
If (pid==0)
break;
}

If (id & lt; 3)
{
//the child 0 1 2
Cout & lt; <"I 'm the child, copying my id=" & lt; //each child process mapping memory copy of
Memcpy (temp_tar + id * wrsize, temp_sor + id * wrsize, wrsize);
}
Else if (id==3)
{
//the child 3
Cout & lt; <"I 'm the child, copying my id=" & lt; //map at the end of the last child process for memory copy of
Memcpy (temp_tar + id * wrsize, temp_sor + id * wrsize, tlsize);
}
Else if (id==4)
{
//parent
int status;
Int ret.
//parent to recycle the child and close the file

While ((ret=waitpid (- getpid (), & amp; The status, 0))!=1)
{
If (WIFEXITED (status))
{
Cout & lt; <"Recover child success! "& lt; }
}

//recovered after the child, the parent disconnect map
Ret=munmap (sor_p filesize);
If (ret & lt; 0)
{
Cout & lt; <"Munmap err!" The return - 4;
}

Ret=munmap (tar_p filesize);
If (ret & lt; 0)
{
Cout & lt; <"Munmap err!" Return to 5;
}

}





return 0;
}


copy the file to open, most can run, but the icon is not correct, I tried others write online program, the somebody else's copy is no problem, where I feel I must have a little problem, but found no problem, I even tried system Ctrl c, Ctrl v, take an examination of to another directory is normal, this let me more confused



  • Related