"Linux" Thread concurrent copy program

Source: Internet
Author: User
Tags create directory fread

It is said that Professor Li of a 211 university in Dalian is getting more and more serious. Not only does it continue to require every undergraduate class he brings. All have to write a copy of the thread and the tradition of copying programs, and also started to rule that can not be written in the Java language. Causes me to write "Java" Thread concurrent copy program (click Open link) void. All of Professor Li's students must be in a Linux system without a graphical interface. Use inside VI to write.

This makes it even more dark for the students to feel that the sky is not bright.

and more importantly. Over the years, research and information on the Internet is still a minority. is still the long-circulated, baseless assertion of the C language version.

Although this procedure has no research value, but the spirit of saving lives. At the same time I took this in-depth study of LINUXC's threading programming mechanism, and I finished it again. In Linux with the most most pure C language complete thread concurrent copy program.

For example, having engaged 3 threads in the Linux system to complete the contents of a in directory A to empty is also a copy of directory B. At the same time according to Professor Li's preferences. Prefix in front of. That is, renaming the target directory.


Some students may say that my graphic Linux system is different from the non-graphical Linux.

In fact, the above code in each version of the Linux system can be executed, only you write C language to use the "Linux" Vi/vim (click Open link) to write, query files and directories, to use the CD command to enter the relevant path, the same time with the dir command to read this directory. If you think VI is difficult to use, you can use the "Linux" WinSCP remote access to the GUI-free Linux system (click the Open link), the code you write in Windows. Get Linux, and then use GCC to compile and execute.

Detailed code such as the following:

#include <stdio.h> #include <stdlib.h> #include <string.h> #include <dirent.h>//output file information # include<sys/stat.h>//infer whether the directory #include<pthread.h>//uses thread char *source_arr[512];//to hold the array of source file paths char * destination_arr[512];//the array that holds the path to the destination file, int source_arr_index=0;//The index of the array that holds the path to the source file, is the for (int i=xx; ...;;.) The Iint destination_arr_index=0;//the index of the array that holds the path to the destination file pthread_mutex_t mutex;//declares a mutually exclusive lock mutexint i=0;//multiple thread functions for this I. Used to record whether the copy is complete, so the ~/* string handler function is treated as a global variable */int endwith (char* S,char c) {//To infer whether the end of the string is "/" and "." if (S[strlen (s) -1]==c) {return 1;} Else{return 0;}} char* str_contact (char* str1,char* str2) {//String connection char* result;result= (char*) malloc (strlen (str1) +strlen (str2) +1);// str1 length +str2 length +\0;if (!result) {//Assuming memory dynamic allocation failed printf ("String connection, memory dynamic allocation failed \ n"); exit (1);} strcat (RESULT,STR1); strcat (RESULT,STR2);//string concatenation return result;} /* Traversal function */int Is_dir (char* path) {//infer if the directory struct stat st;stat (path,&st), if (S_isdir (St.st_mode)) {return 1;} Else{return 0;}} void Read_folder (char* Source_path,char *destination_path) {//Copy directory if (!opendir (destiNation_path) {if (mkdir (destination_path,0777))//If not present, use the MkDir function to create {printf ("Failed to create directory. ");}} Char *path;path= (char*) malloc (512);//equivalent to String Path= "" in other languages, strings in a pure C environment must manage their own size, where the path directly applies for 512 of the space of the location. Splicing Path=str_contact (Path,source_path) for the catalogue;//These three sentences, equivalent to path=source_pathstruct dirent* filename;dir* dp=opendir (path) ;//With dir pointer to this directory while (Filename=readdir (DP)) {//traverse dir Pointer to directory, that is, an array of files.

memset (path,0,sizeof (path));p ath=str_contact (Path,source_path);//Suppose Source_path,destination_path ends with a path delimiter. Then source_path/,destination_path/directly as the path can//otherwise in the Source_path,destination_path after the path delimiter and add the file name, who knows you pass the number of the f:/a or F. :/a/ah? Char *file_source_path;file_source_path= (char*) malloc (file_source_path=str_contact); File_source_path,source _path), if (!endwith (Source_path, '/')) {file_source_path=str_contact (Source_path, "/");} Char *file_destination_path;file_destination_path= (char*) malloc (file_destination_path=str_contact); file_ Destination_path,destination_path), if (!endwith (Destination_path, '/')) {file_destination_path=str_contact ( Destination_path, "/");} Take the file name and the current directory into a full path file_source_path=str_contact (file_source_path,filename->d_name); if (Is_dir (File_source _path)) {//assumed to be a directory if (!endwith (File_source_path, '. ')) {//Not at the same time. End, because Linux has one in all directories. Directories are used to connect to the top level of the directory, must be removed, otherwise recursive, the consequences can not be imagined! File_destination_path=str_contact (file_destination_path,filename->d_name);//processing of the target directory. Take the file name and the current directory into a full path Read_folder (file_soUrce_path,file_destination_path);//recursive call, equivalent to enter this directory to traverse ~}}else{//otherwise. The source files in the destination file in the path to the corresponding array//to the target directory processing, take the file name and the current directory stitching into a complete path file_destination_path=str_contact (file_destination_path, "prefix _ ");//Rename the target file, here to indicate how to add a prefix ~ ^_^ file_destination_path=str_contact (file_destination_path,filename->d_name); source_arr[source_arr_index]=file_source_path;source_arr_index++;d Estination_arr[destination_arr_index]=file_ destination_path;destination_arr_index++;}}} /* Copy function */void copy_file (char* Source_path,char *destination_path) {//Copy file char buffer[1024]; File *in,*out;//defines two streams of files. Read and write for the file separately ((In=fopen (Source_path, "R")) (len;if) {//////open source file stream printf ("Source File open failed!"). \ n "); exit (1);} if ((Out=fopen (Destination_path, "w")) ==null) {//Open the file stream of the destination file printf ("Target file creation failed!") \ n "); exit (1);} int Len;//len is fread read bytes long while ((Len=fread (buffer,1,1024,in)) >0) {//reads data from the source file and puts it into the buffer. The second parameter 1 can also be written as sizeof (char) fwrite (buffer,1,len,out);//writes the buffer data to the target file}fclose (out); fclose (in);} /* Thread run function */void *thread_function (void *arg) {while (I<destination_arr_index) {if (pthread_mutex_lock (&mutex)!=0) {//pair mutually exclusive lock, the critical section starts printf ("%s's mutually exclusive lock creation failed. \ n ", (char *) arg); Pthread_exit (NULL); } if (I<destination_arr_index) {copy_file (source_arr[i],destination_arr[i]);//Copy Single file printf ("%s replication%s to%s succeeded!

\ n ", (char *) arg,source_arr[i],destination_arr[i]); I++;sleep (1);//The thread hangs 1 seconds} else{//otherwise exits pthread_exit (NULL);//Exit thread} p Thread_mutex_unlock (&mutex);//unlock, critical section end sleep (1);//The thread hangs 1 seconds} pthread_exit (NULL);//Exit Thread}/* Main function */int main (int argc, Char *argv[]) {if (argv[1]==null| | Argv[2]==null) {printf ("Please enter two directory paths, the first one is the source. The second one for the purpose!

\ n "); exit (1);} Char* source_path=argv[1];//takes the first parameter entered by the user char* destination_path=argv[2];//takes the second parameter entered by the user dir* Source=opendir (source_ Path);D ir* destination=opendir (Destination_path); if (!source| |! Destination) {printf ("One of the parameters you entered or the second parameter is not a directory! \ n ");} Read_folder (Source_path,destination_path);//Traverse directory Traversal/* thread concurrency Start */pthread_mutex_init (&mutex,null);//Initialize this mutually exclusive lock/ /Declaration and creation of three threads pthread_t T1; pthread_t T2; pthread_t T3; if (Pthread_create (&t1,null,thread_function, "Thread 1")!=0) {printf ("Create thread failed!") The program is over!

\ n "); Exit (1); } if (Pthread_create (&t2,null,thread_function, "Thread 2")!=0) {printf ("Create thread failed!")

The program ends. \ n "); Exit (1); } if (Pthread_create (&t3,null,thread_function, "Thread 3")!=0) {printf ("Create thread failed!")

The program is over! \ n "); Exit (1); } pthread_join (T1,null); Pthread_join (T2,null); Pthread_join (T3,null); Three threads are finished the ability to run the following code Pthread_mutex_destroy (&mutex);//Destroy this mutually exclusive lock/* thread concurrent end */return 0;}


This hundred line of code, there is nothing to say.

First, the program is "Linux" threads mutually exclusive (click the Open link) and "Linux" C language Implementation directory copy (click Open link) of the combination. The concept that I have covered in these two papers has been specifically written. This is no longer a big story.

After that, because it involves a lot of paths to the stitching, to get to the end or "Linux" pure C Environment string processing (click Open link) problem, C language is so annoying, make a string, to use pointers, arrays, functions. And so on a variety of complex concepts to deal with.

"Linux" Thread concurrent copy program

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.