Problem Description:
Open (Pathname, O_RDWR | o_creat,0666); Can't I? Why does a lot of information say to add o_excl, say is atomic operation, do not add is not it?
Answer:
If the file already exists beforehand,
open (pathname, o_rdwr | o_creat,0666); Open successfully, returns an FD
open (pathname, o_rdwr | o_creat | o_excl,0666); Open failed, return-1
O_excl says that if a file exists when using O_creat, it returns an error message that tests whether the file exists.
Imagine a requirement that a task requires only a single process to execute, not multiple processes at the same time.
However, there is no guarantee that multiple processes will start at the same time and try to perform this task.
This further requires that only the first execution of the process can continue, and subsequent attempts to execute the process are all out of error.
one scenario is to try to open a file with an open () with the O_EXCL flag.
The file does not exist when the first process executes, it can successfully create the file and continue execution.
the second and subsequent processes will fail because the file already exists, and the process exits.
If you don't use the O_EXCL flag, your code might want to write this:
if (Access (file, r_ok) = =-1)/* First check if the file exists */
open (file, O_RDWR | o_creat,0666); /* If it does not exist, then I create a file like this * *
.../* continue to perform tasks * /
There is a potential problem with this logic, that is, to determine whether a file exists with the creation of a file is two separate system calls.
If process 1 executes access, it is determined that the file does not exist;
then due to the operating system scheduling policy, Process 1 suspend execution, process 2 execution, process 2 will also determine that the file does not exist.
The end result is that two processes will succeed when they call open and then continue. This allows multiple processes to perform this task at the same time.
What is the use of O_EXCL when opening files in Linux