一、概念介绍
系统调用原子操作的概念:将某一系统调用所需要完成的各个动作作为不可中断的操作一次性加以执行,原子操作是许多操作系统调用得以正确执行的必要条件。
原子操作是内核保证了某系统调用中所有步骤会作为独立操作而一次性加以执行,期间不会为其他进程或者线程所中断。"避免了竞争"
二、举例
以open系统调用为例:
open中 O_CREAT & O_EXCL 一起使用可以避免竞争
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<errno.h>
int main(int argc ,char *argv[])
{
int fd;
fd = open(argv[1], O_WRONLY); /* 没有使用O_EXCL情况 */
if (fd != -1)
{ /* Open succeeded */
printf("[PID %ld] File \"%s\" already exists\n",(long) getpid(), argv[1]);
close(fd);
}
else{