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

#include 
#include 
#include 
#include 
#include 
#include 

#define  N  64

int main(int argc, char *argv[])
{
	int fds, fdt, len, nbyte;
	pid_t pid;
	char buf[N];

	if (argc < 3)
	{
		printf("Usage : %s  \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;
}

你可能感兴趣的:(文件IO,Linux)