进程 day1

该程序是用C语言编写的,用于在Ubuntu系统中通过父子进程协同工作来拷贝文件。程序首先检查命令行参数,然后打开源文件和目标文件。父进程读取源文件的一半内容并写入目标文件,子进程处理剩余的一半。文件操作包括使用open(),read(),write(),lseek()等系统调用,并确保正确处理错误情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

作业: 用父子进程拷贝文件:

ubuntu@ubuntu:~$ cat test6.c
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc,char *argv[])
{
 if(argc!=3)//argv[1]:源文件;argv[2]:目标文件
 {
  perror("You Wrong");
  return -1;
 }
int myread=open(argv[1],O_RDONLY);
if(myread<0)
    return -1;
int mywrite=open(argv[2],O_WRONLY|O_CREAT,0664);
if(mywrite<0)
    return -1;
int len=lseek(myread,0,SEEK_END);

int count=0;
char buf[128];
pid_t pid=fork();

if(pid<0)
    exit(-1);
else if(pid==0)
{

/*int myread=open(argv[1],O_RDONLY);
if(myread<0)
    return -1;
int mywrite=open(argv[2],O_WRONLY|O_CREAT,0664);
if(mywrite<0)
    return -1;*/
    lseek(myread,0,SEEK_SET);
    lseek(mywrite,0,SEEK_SET);
 while(count<=len/2)
 {
 int cread=read(myread,buf,sizeof(buf));
  count=count+cread; 
  if(count>len/2)
      write(mywrite,buf,cread-(count-len/2));
  else
      write(mywrite,buf,cread);
  bzero(buf,sizeof(buf));
 }
}
else
 {
  wait(NULL);
  lseek(myread,len/2+1,SEEK_SET);
  lseek(mywrite,len/2+1,SEEK_SET);
  count=len/2;
  while(count<=len)
  {
    int myr=read(myread,buf,sizeof(buf));
    count=count+myr;
    write(mywrite,buf,sizeof(buf));
    bzero(buf,sizeof(buf)); 
  }

 }
close(myread);
close(mywrite);
 return 0;
}
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值