现在的位置: 首页 > 综合 > 正文

文件复制(多进程实现-适合各种项目参考)

2013年10月21日 ⁄ 综合 ⁄ 共 1642字 ⁄ 字号 评论关闭
#include "apue.h"
#define  PATH   "1.db"
  
void sig_alrm(int signo)
{
	printf("signo=%u pid=%u tid=%u   \n", 
			(unsigned int )signo, (unsigned int )getpid(), (unsigned int )pthread_self());
	return ;
}

unsigned long  get_file_size(const char *path)  
{  
    unsigned long filesize = -1;      
    struct stat statbuff;  
    if(stat(path, &statbuff) < 0)
    {  
        return filesize;  
    }
    else
    {  
        filesize = statbuff.st_size;  
    }  
    return filesize;  
}  

int file_cp(const char *src,const char *dest)
{
    char * buf[1024];
    int len;
    int fr,fd;
    int ret;
    fr =open(src,O_RDONLY);
        perror(src);
    fd = open(dest,O_WRONLY|O_CREAT) ;
        perror(dest);
    while( fr>0 && fd>0 )
        {
                memset(buf, 0, sizeof(buf));
                len = read(fr, buf, sizeof(buf));
                if( len  <  0 )
                    {
                        break;
                    }
                else if(len == 0)
                    {
                        break;
                    }
                ret = write(fd, buf, len);
                if(ret < 0)
                    {
                        break;
                    }
        }
        close(fd);                                                       
        close(fr);
}


int get_local_time(char *p)
{
        time_t   now;
        struct   tm     *timenow;        
        time(&now);
        timenow=localtime(&now);
        printf("Local time is %s/n",asctime(timenow));
	
        asctime(timenow);
}

void *thread_fun(void *arg)
{
	struct sigaction act,oact;//设置信号	
	act.sa_handler =sig_alrm;
	act.sa_flags = 0;
	sigemptyset(&act.sa_mask);
	sigaction(SIGALRM, &act, &oact);
	while(1)
	{
		printf("pid=%d tid=%u\n",(int) getpid(), (unsigned int)pthread_self());
		unsigned long      size ;
		printf("3\n");
		//size = get_file_size(PATH);
		char  buf[55];
		strcat(buf,"_backup.db");
       		 
		time_t   now;
       		struct   tm     *timenow;        
      		time(&now);
       		timenow=localtime(&now);
                printf("Local time is %s/n",asctime(timenow));
		strcpy(buf,(asctime(timenow)));
		strcat(buf,"_backup.db");
		printf("4\n");
		//buf=get_locak_time;
		if(size>1)
			{
		printf("5\n");
				file_cp(PATH,buf);
		printf("6\n");
			}
		sleep(1);
	}
	
//		printf("7\n");
}
int main()
{
	pthread_t thread_id;
	pthread_create(&thread_id, NULL, thread_fun, NULL);
	sleep(3);
	//raise(SIGALRM);//向某一进程发送信号,由进程处理
	pthread_kill(thread_id, SIGALRM);//向某一线程发送信号,由接受线程处理
	pthread_join(thread_id, NULL);//进程接受信号和线程接受信号不同

}

抱歉!评论已关闭.