When multiple processes open the same file to write logs, the o_append parameter is specified during open. UNIX can ensure that this operation is atomic,ProgramNo need to lock yourself
/* 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 ); // Enable CPU scheduling 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 ); // Enable CPU scheduling 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 ); // Enable CPU scheduling 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 ); // Enable CPU scheduling Write (FD, MSG, strlen (MSG); write (stdout_fileno, MSG, strlen (MSG);} Close (FD ); Return 0 ;}