打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
同一个文件共同读写(open中O

现来看二个程序。

#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一直阻塞,直到写完。

对于 dup 会共享同一个文件表,对于open()同一个文件,此时会有一个新的文件 表状态。
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
磁盘文件操作
如何在proc目录下增加设备文件
C语言安全文件传输程序设计。
Linux下C语言编程--文件的操作
UC头条:Linux基础IO[文件操作]
linux下的umask()函数
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服