20240104(Linux 进程)作业

创建出三个进程完成两个文件之间拷贝工作,子进程1拷贝前一半内容,子进程2拷贝后一半内容,父进程回收子进程的资源
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>

int main(int argc, const char *argv[])
{
	if(argc<3){
		printf("the number of argument should be at least 3\n");
		printf("usage:./a.out sourceFileName destinationFileName\n");
		return -1;
	}

	int sfd=-1;
	int dfd=-1;
	if((sfd=open(argv[1],O_RDONLY))==-1){
		perror("open source file error");
		return -1;
	}
	if((dfd=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC,0664))==-1){
		perror("open destination file error");
		return -1;
	}

	//calculate the size of source file
	off_t srcFileSize=lseek(sfd,0,SEEK_END);

	//char buf[20]="";

	pid_t pid=-1;
	/*--------------------------------the 1st child process*/
	pid=fork();
	if(pid==-1){
		perror("fork error 1");
		return -1;
	}
	if(pid==0){
		//the 1st child process copy the first half of the source file
		int res=-1;
		int curPos=0;
		char buf[10]="";
		while(curPos<=srcFileSize/2){
			lseek(sfd,curPos,SEEK_SET);
			res=read(sfd,buf,sizeof(buf));
			lseek(dfd,curPos,SEEK_SET);
			write(dfd,buf,res);
			curPos+=res;
		}
		printf("I am 1st child and my part copy is done!!!\n");

		exit(EXIT_SUCCESS);
	}

	/*--------------------------------the 2nd child process*/
	pid=fork();
	if(pid==-1){
		perror("fork error 2");
		return -1;
	}
	if(pid==0){	
		//the 2nd child process copy the second half of the source file
		int res=-1;
		int curPos=srcFileSize/2+1;
		char buf[10]="";
		while(curPos<srcFileSize){
			lseek(sfd,curPos,SEEK_SET);
			res=read(sfd,buf,sizeof(buf));
			lseek(dfd,curPos,SEEK_SET);
			write(dfd,buf,res);
			curPos+=res;
		}
		printf("I am 2nd child and my part copy is done!!!\n");
		exit(EXIT_SUCCESS);
	}
	/*--------------------------------the parent process*/
	printf("I am parent process and waiting for the copy finishing ...... \n");

	wait(NULL);
	wait(NULL);
	close(dfd);
	close(sfd);
	printf("file copied succesfully!\n");

	return 0;
}

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值