1 #include <stdio.h>
2 #include <sys/stat.h>
3 #include <sys/types.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6
7 int main(int argc, const char *argv[])
8 {
9 int fd_r = open("./1zh.jpg", O_RDONLY);
10 if(fd_r < 0)
11 {
12 // printf("");
13 perror("open");
14 return -1;
15 }
16
17 int fd_w =open("cpy.jpg", O_WRONLY|O_CREAT|O_TRUNC, 0664);
18 if(fd_w < 0)
19 {
20 // printf("");
21 perror("open");
22 return -1;
23 }
24
25 off_t size = lseek(fd_r, 0, SEEK_END);
26
27 //子进程
28 pid_t pid = fork();
29 if(pid > 0)
30 {
31 char arr1[10];
32 sprintf(arr1, "%d", fd_r);
33 char arr2[2];
34 sprintf(arr2, "%d", fd_w);
35 char arr3[10];
36 sprintf(arr3, "%ld", size);
37
38 execl("p", arr1, arr2, arr3, NULL);
39 }
40 else if(0 == pid)
41 {
42 //子进程修改到中间位置
43 lseek(fd_r, size/2, SEEK_SET);
44 lseek(fd_w, size/2, SEEK_SET);
45
46 char c;
47 for(int i =0; i<size/2; i++)
48 {
49 read(fd_r, &c, 1);
50 write(fd_w, &c, 1);
51 }
52 printf("后半部分拷贝完毕\n");
53 }
54 else
55 {
56 perror("fork");
57 return -1;
58 }
59
60 close(fd_r);
61 close(fd_w);
62 return 0;
1 #include <stdio.h>
2 #include <sys/stat.h>
3 #include <sys/types.h>
4 #include <unistd.h>
5 #include <fcntl.h>
6 #include <stdlib.h>
7 int main(int argc, const char *argv[])
8 {
9 int fd_r = atoi(argv[0]);
10 int fd_w =atoi(argv[1]);
11 off_t size = atoi(argv[2]);
12
13 sleep(4);
14 lseek(fd_r, 0, SEEK_SET);
15 lseek(fd_w, 0, SEEK_SET);
16
17 char c;
18 for(int i = 0; i<size/2; i++)
19 {
20 read(fd_r, &c, 1);
21 write(fd_w, &c, 1);
22 }
23 printf("前半部分拷贝完毕\n");
24
25 close(fd_r);
26 close(fd_w);
27 return 0;
28 }
~
~
~
~
~
~
~
1 #include<stdio.h>
2 #include <sys/stat.h>
3 #include <sys/types.h>
4 #include <unistd.h>
5 #include <pthread.h>
6 #include <string.h>
7
8 char buf[]="1234567";
9
10 void* A(void* arg)
11 {
12 while(1)
13 {
14 printf("A线程: %s\n",buf);
15 }
16 pthread_exit(NULL);
17 }
18
19
20 void* B(void* arg)
21 {
22 while(1)
23 {
24 char t;
25 int i=0;
26 int j=strlen(buf)-1;
27 while(i<j)
28 {
29 t=buf[i]; buf[i]=buf[j]; buf[j]=t;
30 i++;j--;
31 }
32 }
33 pthread_exit(NULL);
34 }
35 int main(int argc, const char *argv[])
36 {
37 pthread_t tid, tid1;
38 if(pthread_create(&tid,NULL,A,NULL)!= 0)
39 {
40 fprintf(stderr,"pthread_create failed");
41 return -1;
42 }
pthread_detach(tid1);
43 if(pthread_create(&tid1,NULL,B,NULL)!= 0)
44 {
45 fprintf(stderr,"pthread_create failed");
46 return -1;
47 }
48
50 pthread_join(tid, NULL);
51
52
53
54 return 0;
55 }
~
~
~
~
分析:经过测试,将子进程A使用pthread_detach函数加入到创建进程A的程序下时候可以避免乱码的输出,
分离A线程; 被分离的A线程的资源将被自动回收,不需要使用pthread_join回收了; 当tid线程被分离后,phtread_join tid线程不阻塞,线程A不会再输出线程B过程中未全部的完成的过程乱码。
标签:char,lseek,exec,int,父子,fd,线程,拷贝,include From: https://blog.csdn.net/qq_51852604/article/details/139634767