Linux fork 多进程 实现拷贝文件 四个进程拷贝

kxh1234 2017-10-11 07:55:52

我的代码

请各位帮我找找问题

#include<stdio.h>
#include<sys/wait.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{

char buf[1024];
int fd=open(argv[1],O_RDONLY);
if(fd==-1)
{
perror("open source file failed!");
exit(1);
}

int fd1=open(argv[2],O_WRONLY |O_CREAT| O_EXCL,0777);
if(fd1==-1)
{
perror("open tap file failed!");
exit(1);
}

int len=lseek(fd,0,SEEK_END);

if(len==-1)
{
perror("lseek failed!");
exit(1);
}
int block_size=len%4+1;
// char *buf=NULL;
//char buf[1024];
int i=0;
int pid;
for(i=0;i<3;i++)
{
pid=fork();
if(pid==0)
break;

}
int n=read(fd,buf,block_size);
if(n<0)
{
perror("read failed!");
exit(0);
}
int m=write(fd1,buf,n);

if(pid>0)
while(wait(NULL));

//free(buf);
close(fd);
close(fd1);
return 0;

}[/code]
...全文
429 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
heronism 2017-11-30
  • 打赏
  • 举报
回复
引用
这样做应是没什么用的,不会把数据复制4份,也不会用4个进程同时复制一段内容。 因为fork进程时,会把进程复制一份,包括文件描述符,而且每个文件描述的读写位置都是一样的。 如果是想4个进程同时写一段内容的话,每个进程需要从同一个文件里读出不同位置的内容,再写到另同一个文件的不同位置上。
高手,正解!
jklinux 2017-10-13
  • 打赏
  • 举报
回复
这样做应是没什么用的,不会把数据复制4份,也不会用4个进程同时复制一段内容。 因为fork进程时,会把进程复制一份,包括文件描述符,而且每个文件描述的读写位置都是一样的。 如果是想4个进程同时写一段内容的话,每个进程需要从同一个文件里读出不同位置的内容,再写到另同一个文件的不同位置上。

23,120

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧