#include
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
//#include <memry.h>
#include <error.h>
#include <string.h>
#include <wait.h>
/*
removeFile(const char *filename)
{
char str_result[512]={0};
char str_stemp[512]={0};
char str_cmd[512]={0};
FILE *fpread;
fprinf(str_cmd, "rm -f %s", filename);
if(fpread=popen())
}
*/
int copyFile(const char *srcFile, const char *dstFile)
{
int fdin, fdout;
void *src, *dst;
struct stat st;
if(!srcFile || !dstFile || (0==strlen(srcFile)) || (0==strlen(dstFile)))
return -1;
if((fdin=open(srcFile, O_RDONLY)) return -1;
if(0!=fstat(fdin, &st))
return -1;
if(!S_ISREG(st.st_mode))
return -1;
if(st.st_size return -1;
//char str_cmd[512]={0};
//fprintf(str_cmd, "rm -f %s", dstFile);
system("rm -f zlh");
umask(00000);
if((fdout=open(dstFile, O_RDWR|O_CREAT, S_IRWXU|S_IRGRP|S_IROTH)) return -1;
lseek(fdout, st.st_size, SEEK_SET);
write(fdout, "", 1);
src=mmap(0, st.st_size, PROT_READ, MAP_SHARED, fdin, 0);
if(src==MAP_FAILED)
return -1;
dst=mmap(0, st.st_size, PROT_WRITE|PROT_READ, MAP_SHARED, fdout, 0);
if(dst==MAP_FAILED)
return -1;
close(fdin);
close(fdout);
memcpy(dst, src, st.st_size);
msync(src, st.st_size, MS_SYNC);
msync(dst, st.st_size, MS_SYNC);
if(-1==munmap(src, st.st_size))
return -1;
if(-1==munmap(dst, st.st_size))
return -1;
return 0;
}
int main(int argc, char **argv)
{
const char *srcFile="/home/zlh/starter/abc.bak";
const char *dstFile="/home/zlh/starter/abc";
//setenv("LD_PRELOAD", "libachk.so", 1);
int p1[2], p2[2];
int cmd, i = 1;
pipe(p1);
pipe(p2);
fcntl(p1[0], F_SETFL, O_NONBLOCK);
//fcntl(p2[0], F_SETFL, O_NONBLOCK);
int iresult=copyFile(srcFile, dstFile);
if(-1==iresult)
return -1;
pid_t pid=fork();
if(pid>0)
{
close(p1[0]);//p1 读端
close(p2[1]);//p2 写端
printf("parent...000...\n");
/* read from p2 to wait for child complete */
read(p2[0], &cmd, sizeof(cmd));
printf("parent...111...\n");
int ires=execl("/home/zlh/starter/abc", "abc", NULL);
if(ires {
printf("parent...222...\n");
/* write to p1 to tell child continue */
cmd = i;
write(p1[1], &cmd, sizeof(cmd));
}
printf("parent...333...\n");
//}
/* -1 to tell child quit */
cmd = -1;
write(p1[1], &cmd, sizeof(cmd));
wait(NULL);
printf("Parent done, quit...\n");
}
else
{
printf("child ...000\n");
close(p1[1]);
close(p2[0]);
printf("child...111...\n");
/* write to p2 to tell parent continue */
write(p2[1], &cmd, sizeof(cmd));
while(read(p1[0], &cmd, sizeof(cmd)) == sizeof(cmd)&& cmd >= 0)
{
printf("child...222...%c\n", 'A'+(i%26));
/* write to p2 to tell parent continue */
write(p2[1], &cmd, sizeof(cmd));
}
if(1==getppid())
printf("child...333...parent exit...\n");
printf("\n\nChild receive finish command from parent, quit...\n");
exit(0);
}
return 0;
}