#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int flag = 0;
void* task(void* arg){
puts("child thread start");
while(!flag){
puts("child thread sleeping...");
sleep(1);
}
int fd = *(int *)arg;
char buf[64] = {};
lseek(fd, 0, SEEK_SET);
int ret = read(fd, buf, sizeof(buf));
printf("child thread read %d byte(s): %s\n", ret, buf);
puts("child thread end");
return NULL;
}
void getLine(char* buf){
char ret, i = 0;
while((ret = fgetc(stdin)) != EOF && ret != '\n')
buf[i++] = ret;
}
int main(int argc, const char *argv[])
{
puts("main thread start");
int fd = open(argv[1], O_CREAT|O_RDWR|O_TRUNC, S_IRWXU);
if(-1 == fd){
perror("open");
return 1;
}
pthread_t tid;
int ret = pthread_create(&tid, NULL, task, &fd);
if(ret){
perror("pthread create");
return 1;
}
char buf[64] = {};
getLine(buf);
while(flag);
ret = write(fd, buf, strlen(buf));
flag = 1;
printf("write %d byte(s)\n", ret);
puts("main thread wait for child thread to join...");
pthread_join(tid, NULL);
close(fd);
puts("main thread end");
return 0;
}
5.10 作业+思维导图
最新推荐文章于 2024-10-18 11:06:32 发布