-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmulti_thread.c
More file actions
81 lines (70 loc) · 1.57 KB
/
multi_thread.c
File metadata and controls
81 lines (70 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
void* print_time(void * arg)
{
FILE *fp = NULL;
time_t now;
struct tm *mytm;
pthread_detach(pthread_self());
fp = fopen ("time.log","a+");
if (fp == NULL) {
return NULL;
}
while(1){
now = time(NULL);
mytm = localtime(&now);
fprintf(fp,"%d-%d-%d %d:%d:%d\n",mytm->tm_year+1900,mytm->tm_mon+1,\
mytm->tm_mday,mytm->tm_hour,mytm->tm_min,mytm->tm_sec);
fflush(fp);
sleep(1);
}
}
void* terminal_input(void *arg)
{
int fd,len;
char buf[100];
FILE *fp;
pthread_detach(pthread_self());
printf("input content to record\n");
fp = fopen ("terminal.log","a+");
if (fp == NULL) {
return NULL;
}
while(1) {
len = read(STDIN_FILENO,buf,100);
if (len > 0) {
printf("continue...\n");
fwrite(buf, 1, len, fp);
fflush(fp);
}
sleep(1);
}
}
int create_thread(void)
{
pthread_t tid_time, tid_input;
int ret;
if (0 !=pthread_create(&tid_time, NULL, print_time, NULL)){
printf("print time create failed:\n");
return -1;
}
ret = pthread_create(&tid_time, NULL, terminal_input, NULL);
if(ret != 0) {
printf("print time create failed:%s\n",strerror(ret));
return -1;
}
sleep(60);
printf("end thread\n");
pthread_cancel(tid_time);
pthread_cancel(tid_input);
return 0;
}
int main(void)
{
printf("start\n");
create_thread();
return 0;
}