父子进程实现图片拷贝

父进程拷贝前半部分,子进程拷贝后半部分:最简单的方法

#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include<errno.h>
#include <sys/stat.h> 
#include <fcntl.h>
#define MSG(msg) {printf("--%d",__LINE__);perror(msg);}
int main(int argc, const char *argv[])
{
	
	pid_t pid=fork();
	if(pid<0)
	{

		MSG("fork");
		return -1;
	}
	//父进程拷贝前半部分
	if(pid>0)
	{
		int fp=open("./001.png",O_RDONLY);
		if(fp<0)
		{
			MSG("open");
			return -1;
		}
		int length;//获取文件大小
		length=lseek(fp,0,SEEK_END);
		lseek(fp,0,SEEK_SET);
		int fp_w=open("./copy.png",O_WRONLY|O_CREAT|O_TRUNC,0664);
		if(fp_w<0)
		{
			MSG("open");
			return -1;
		}
		size_t res=0;
		char arr[length/2];
		res=read(fp,arr,sizeof(arr));
		printf("res=%ld\n",res);
		write(fp_w,arr,res);
		close(fp);
		close(fp_w);
	}
	//子进程拷贝后半部分
	if(pid==0)
	{
		int fp=open("./001.png",O_RDONLY);
		if(fp<0)
		{
			MSG("open");
			return -1;
		}
		int length;//获取文件大小
		length=lseek(fp,0,SEEK_END);
		lseek(fp,length/2,SEEK_SET);
		int fp_w=open("./copy.png",O_WRONLY|O_CREAT|O_APPEND,0664);
		if(fp_w<0)
		{
			MSG("open");
			return -1;
		}
		size_t res=0;
		char arr[length-length/2];
		res=read(fp,arr,sizeof(arr));
		printf("res=%ld\n",res);
		write(fp_w,arr,res);
		close(fp);
		close(fp_w);
	}
	
	return 0;
}

效果展示:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
子进程拷贝文件,你可以使用Python的`multiprocessing`模块来创建子进程,并使用操作系统提供的文件操作函数来完成文件拷贝。下面是一个示例代码,演示了如何在子进程拷贝文件: ```python import os import shutil from multiprocessing import Process def copy_file(source_file, target_file): try: with open(source_file, 'rb') as src, open(target_file, 'wb') as dst: # 以二进制模式打开源文件和目标文件 shutil.copyfileobj(src, dst) # 使用shutil模块的copyfileobj函数拷贝文件内容 print("文件拷贝成功") except IOError: print("文件拷贝失败") def copy_file_in_child_process(source_file, target_file): pid = os.fork() # 创建子进程 if pid == 0: # 子进程 copy_file(source_file, target_file) os._exit(0) # 子进程执行完毕后退出 else: # 进程 pid, status = os.waitpid(pid, 0) # 等待子进程结束 if os.WEXITSTATUS(status) == 0: print("子进程执行成功") else: print("子进程执行失败") # 使用示例 source_path = 'path/to/source/file.txt' target_path = 'path/to/target/file.txt' copy_file_in_child_process(source_path, target_path) ``` 在这个示例代码中,我们定义了`copy_file()`函数,该函数与之前的示例代码中的函数相同,用于拷贝文件。然后,我们定义了`copy_file_in_child_process()`函数,该函数创建一个子进程,并在子进程中调用`copy_file()`函数来拷贝文件。进程使用`os.waitpid()`函数等待子进程结束,并根据子进程的执行状态进行处理。 请将示例代码中的`source_path`和`target_path`替换为实际的文件路径。这个示例代码会先创建一个子进程,然后在子进程中执行文件拷贝操作。进程会等待子进程结束后打印相应的信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值