同一个文件共同读写(open中O_SYNC用法)

现来看二个程序。

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>


int main()
{
    int fd;
    if((fd=open("test",O_RDWR|))<0)
    {
        perror("open");
        return -1;
    }

    lseek(fd,-3,SEEK_END);
    char buffer[32]="hello";
    sleep(10);
    write(fd,buffer,strlen(buffer));
    close(fd);
    return 0;
}

另一个程序

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>


int main()
{
    int fd;
    if((fd=open("test",O_RDWR|))<0)
    {
        perror("open");
        return -1;
    }

    lseek(fd,-3,SEEK_END);
    char buffer[32]="33333333333";//修改的地方
    sleep(5);//修改的地方
    write(fd,buffer,strlen(buffer));
    close(fd);
    return 0;
}

test文件的内容是

1111111111111
2222222222222

这个时候2个程序同时运行,将会怎样呢 ,运行结果如下

pipi@ubuntu:~/c$ cat test
1111111111111
222222222223333333333333333pipi@ubuntu:~/c$ cat test
1111111111111
222222222223333333333333333pipi@ubuntu:~/c$ cat test
1111111111111
222222222223333333333333333pipi@ubuntu:~/c$ cat test
1111111111111
222222222223333333333333333pipi@ubuntu:~/c$ cat test
1111111111111
22222222222hello33333333333pipi@ubuntu:~/c$

 

也就是说打开文件后,系统不会自动更新文件写的位置,对于每个“文件状态标志”和“当前文件偏移量” 不会更新。

对于多进程的时候:

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>


int main()
{
    int fd;
    if((fd=open("test",O_RDWR|O_SYNC))<0)
    {
        perror("open");
        return -1;
    }

    pid_t pid;
    if((pid=fork())<0)
    {
        perror("fork");
        return -1;
    }

    if(pid==0)
    {    
        lseek(fd,-3,SEEK_END);
        char buffer[32]="333333333333";
        sleep(2);
        write(fd,buffer,strlen(buffer));
        printf("child quit/n");
        close(fd);
    }
    else
    {
        lseek(fd,-5,SEEK_END);
        char buffer[32]="hello";
        sleep(6);
        write(fd,buffer,strlen(buffer));
        close(fd);

    }
    return 0;
}

结果是:

pipi@ubuntu:~/c$ cat test
1111111111111
2222222222222
pipi@ubuntu:~/c$ cat test
1111111111111
22222222222333333333333pipi@ubuntu:~/c$ cat test
1111111111111
22222222222333333333333hellopipi@ubuntu:~/c$

系统会自动更新文件指针,这个时候是由于进程共享同一个文件描述符,同时共享文件表和当前文件偏移量。

 

对于open()中参数O_SYNC的应用,在写文件的时候,未写完的时候,中断或者系统调度或者SMP环境的时候,write一直阻塞,直到写完。

你可能感兴趣的:(同一个文件共同读写(open中O_SYNC用法))