通过父子进程完成文件io对文件的拷贝,父进程从文件开始到文件 的一半开始拷贝,子进程从文件的一半到文件末尾。

2017-09-13 20:43:36来源:CSDN作者:Masup123人点击

分享
#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <fcntl.h>#include <sys/types.h>#include <sys/wait.h>#define  N  64int main(int argc, char *argv[]){	int fds, fdt, len, nbyte;	pid_t pid;	char buf[N];	if (argc < 3)	{		printf("Usage : %s <src_file> <dst_file>/n", argv[0]);		return -1;	}	if ((fds = open(argv[1], O_RDONLY)) < 0)	{		perror("fail to open");		exit(-1);	}	if ((fdt = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, 0666)) < 0)	{		perror("fail to open");		exit(-1);	}	len = lseek(fds, 0, SEEK_END);	len /= 2;	if ((pid = fork()) < 0)	{		perror("fail to fork");		exit(-1);	}	else if (pid == 0)	{		close(fds);		close(fdt);		fds = open(argv[1], O_RDONLY);		fdt = open(argv[2], O_WRONLY);		lseek(fds, len, SEEK_SET);		lseek(fdt, len, SEEK_SET);		while ((nbyte = read(fds, buf, N)) > 0)		{			write(fdt, buf, nbyte);		}		close(fds);		close(fdt);	}	else	{		lseek(fds, 0, SEEK_SET);		while (len > 0)		{			nbyte = read(fds, buf, N);			write(fdt, buf, nbyte);			len -= nbyte;		}		close(fds);		close(fdt);		wait(NULL);	}	return 0;}

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台