1. 程式人生 > >Linux 實現多程序拷貝檔案

Linux 實現多程序拷貝檔案

//copy.c
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include<stdlib.h>
#include<sys/stat.h>
#include<errno.h>
#include <sys/wait.h>

int main(int argc,char *argv[]) {
    if(argc<4)
    {
         printf("please input args like \' copy src des prcnum\'");
         exit(1);
     }
     int fd = open(argv[1],O_RDONLY);
     if(fd<0)
     {
         perror("src:");
         exit(errno);
     }
     struct stat srcinfo;
     int statre = stat(argv[1],&srcinfo);
     if(statre !=0)
     {
         perror("stat failed");
         exit(errno);
     }
     close(fd);
     int numCount = atoi(argv[3]);
     int seeksize = srcinfo.st_size / numCount + (srcinfo.st_size% numCount>0?1:0);
     while (numCount--)
     {
         printf("%d\n",numCount);
         int pid = fork();
         if(pid == 0)
         {
             int csfd = open(argv[1],O_RDONLY);
             if (csfd<0)
             {
                 perror("open fild");
                 exit(errno);
             }
             int cdfd = open(argv[2],O_RDWR|O_CREAT,0777);
             int redseek = lseek(cdfd,seeksize*numCount,SEEK_SET);
             int resseek = lseek(csfd,seeksize*numCount,SEEK_SET);
             if (redseek < 0)
             {
                 perror("reseek:");
                 exit(errno);
             }
             char buf[1024];
             int rednum = 0;
             int flag = 0;
             while ((rednum =read(csfd,buf, sizeof(buf)))!=0)
             {
                  flag+=rednum;
                 if(flag>seeksize)
                 {
                     rednum = seeksize -(flag - rednum) ;
                     write(cdfd,buf,rednum);
                     break;
                 }
                 write(cdfd,buf,rednum);
             }
             close(csfd);
             close(cdfd);
             break;
         }

     }
     //非阻塞等待兒子程序gg
     while (waitpid(-1, NULL,WNOHANG)!=-1)
     {
         printf(" I am wait my son!\n");
         sleep(2);
     }
     return 0;
 }

linux下利用fork實現多程序拷貝檔案。本程式拷貝的是就是其本身copy.c檔案。本程式碼只注重實現,容錯處理並未加全。純原創,歡迎留言討論指出bug。