当多个进程打开同一个文件写入日志的时候,OPEN时指定了O_APPEND参数,UNIX能保证这个操作是原子的,程序不需要自己加锁

/*log1.c*/
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>

int Max = 300;
int main()
{
    int i;
    int fd;
    fd = open("1.log",O_WRONLY | O_APPEND);
    for(i=0;i<Max;i++)
    {
        char msg[100];
        sprintf(msg,"log1: message %d...\n",i);
        sleep(1);//让CPU调度走
        write(fd,msg,strlen(msg));
        write(STDOUT_FILENO,msg,strlen(msg));
    }
    close(fd);
    return 0;    
}

 

/*log2.c*/
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>

int Max = 300;
int main()
{
    int i;
    int fd;
    fd = open("1.log",O_WRONLY | O_APPEND);
    for(i=0;i<Max;i++)
    {
        char msg[100];
        sprintf(msg,"log2: message %d...\n",i);
        sleep(1);//让CPU调度走
        write(fd,msg,strlen(msg));
        write(STDOUT_FILENO,msg,strlen(msg));
    }
    close(fd);
    return 0;    
}

 

/*log3.c*/
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>

int Max = 300;
int main()
{
    int i;
    int fd;
    fd = open("2.log",O_WRONLY);
    for(i=0;i<Max;i++)
    {
        char msg[100];
        sprintf(msg,"log3: message %d...\n",i);
        lseek(fd,0,SEEK_END);
        sleep(1);//让CPU调度走
        write(fd,msg,strlen(msg));
        write(STDOUT_FILENO,msg,strlen(msg));
    }
    close(fd);
    return 0;    
}

 

/*log4.c*/
#include<stdio.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>

int Max = 300;
int main()
{
    int i;
    int fd;
    fd = open("2.log",O_WRONLY);
    for(i=0;i<Max;i++)
    {
        char msg[100];
        sprintf(msg,"log4: message %d...\n",i);
        lseek(fd,0,SEEK_END);
        sleep(3);//让CPU调度走
        write(fd,msg,strlen(msg));
        write(STDOUT_FILENO,msg,strlen(msg));
    }
    close(fd);
    return 0;    
}

 

相关文章:

  • 2022-01-24
  • 2022-01-15
  • 2021-08-01
  • 2022-02-07
猜你喜欢
  • 2022-02-03
  • 2021-07-05
相关资源
相似解决方案