1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <pthread.h>
5 #include <sys/types.h>
6 #include <sys/stat.h>
7 #include <fcntl.h>
8 #include <unistd.h>
9 typedef struct Copy
10 {
11 int op;
12 int on;
13 off_t amount;
14
15
16 }copy;
17 void* copy_bhalf(void *argv);
18 void* copy_fhalf(void * argv);
19 pthread_mutex_t matex;
20 int main(int argc, const char *argv[])
21 {
22
23 pthread_mutex_init(&matex,NULL);
24 int op=open("5.c",O_RDONLY);
25 int on=open("6.text",O_WRONLY|O_CREAT|O_TRUNC,0664);
26 off_t amount=lseek(op,0,SEEK_END);
27 pthread_t tid1;
28 pthread_t tid2;
29 copy p;
30 p.on=on;
31 p.op=op;
32 p.amount=amount;
33 if( pthread_create(&tid1,NULL,copy_fhalf,(void*)&p)!=0)
34 {
35 printf(" %d ",__LINE__ );
36 return -1;
37 }
38 if(pthread_create(&tid2,NULL,copy_bhalf,(void*)&p)!=0)
39 {
40 printf(" %d ",__LINE__);
41 }
42 pthread_join(tid1,NULL);
43 pthread_join(tid2,NULL);
44 pthread_mutex_destroy(&matex);
45
46
47
48 return 0;
49 }
50 void* copy_fhalf(void * argv)
51 {
52 int op=((copy*)argv)->op;
53 int on=((copy*)argv)->on;
54 off_t aount=((copy*)argv)->amount;
55 int i=0;
56 char a=0;
57 pthread_mutex_lock(&matex);
58 lseek(op,0,SEEK_SET);
59 lseek(on,0,SEEK_SET);
60 for(i;i<(aount/2);i++)
61 {
62 read(op,&a,1);
63 write(on,&a,1);
64 }
65 pthread_mutex_unlock(&matex);
66
67 }
68 void* copy_bhalf(void *argv)
69 {
70 int op=((copy*)argv)->op;
71 int on=((copy*)argv)->on;
72 off_t aount=((copy*)argv)->amount;
73 char a;
74 int rea;
75 pthread_mutex_lock(&matex);
76 lseek(op,aount/2,SEEK_SET);
77 lseek(on,aount/2,SEEK_SET);
78 while(1)
79 {
80 rea=read(op,&a,1);
81 if(rea==0)
82 break;
83 write(on,&a,1);
84 }
85 pthread_mutex_unlock(&matex);
86
87 }
~
~
~