#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#define filePath "/mnt/My/MutxThread/file.log"
sem_t sem_1, sem_2;
int num = 0;
int fd = 0;
unsigned char *writeLog;
static int count = 5;
static pthread_t thread_flag = 0;
int *do_Thread_1(void *data)
{
int ret;
count = 5;
// printf("%s: begin to write\n",__func__);
while(1)
{
ret = write(fd, "123", 3);
printf("%s:count = %d ret = %d\n", __func__,count, ret);
sleep(1);
count--;
if(!count)
pthread_exit(0);
}
}
void init_file()
{
unsigned char i = 0;
if(!access(filePath, F_OK))
{
fd = open(filePath, O_APPEND | O_RDWR, 0777);
printf("%s:open file success\n",__func__);
}
else
{
fd = open(filePath, O_CREAT | O_RDWR, 0777);
printf("%s: create file\n",__func__);
}
if(fd < 0)
{
printf("%s: open file failed\n",__func__);
}
}
void create_thread()
{
pthread_create(&thread_flag, NULL, do_Thread_1, NULL);
}
void close_file()
{
printf("%s:",__func__);
if(fd>0)
close(fd);
fd = 0;
}
void test_thread()
{
int *ret;
retry:
init_file();
create_thread();
goto retry;
//while(1)
// sleep(1);
}
void main()
{
writeLog = "123456789";
test_thread();
}
#include <semaphore.h>
#include <pthread.h>
#include <fcntl.h>
#include <unistd.h>
#define filePath "/mnt/My/MutxThread/file.log"
sem_t sem_1, sem_2;
int num = 0;
int fd = 0;
unsigned char *writeLog;
static int count = 5;
static pthread_t thread_flag = 0;
int *do_Thread_1(void *data)
{
int ret;
count = 5;
// printf("%s: begin to write\n",__func__);
while(1)
{
ret = write(fd, "123", 3);
printf("%s:count = %d ret = %d\n", __func__,count, ret);
sleep(1);
count--;
if(!count)
pthread_exit(0);
}
}
void init_file()
{
unsigned char i = 0;
if(!access(filePath, F_OK))
{
fd = open(filePath, O_APPEND | O_RDWR, 0777);
printf("%s:open file success\n",__func__);
}
else
{
fd = open(filePath, O_CREAT | O_RDWR, 0777);
printf("%s: create file\n",__func__);
}
if(fd < 0)
{
printf("%s: open file failed\n",__func__);
}
}
void create_thread()
{
pthread_create(&thread_flag, NULL, do_Thread_1, NULL);
}
void close_file()
{
printf("%s:",__func__);
if(fd>0)
close(fd);
fd = 0;
}
void test_thread()
{
int *ret;
retry:
init_file();
create_thread();
/**pthread_join()函数有自动销毁内存资源的功能,所以我们在退出线程,重新创建的时候不用考虑内存资源的问题**/
pthread_join(thread_flag, &ret);
close_file();goto retry;
//while(1)
// sleep(1);
}
void main()
{
writeLog = "123456789";
test_thread();
}