linux2线程写1文件,linux 下多线程写文件

linux 下多线程给文件加排他锁

利用flock 函数,具体用户请自己查。

执行流程

1,创建 /dev/shm/test文件,并打开文件。

2,fork 一个子进程

在子进程中再次打开文件,目的是不和父进程使用不一样的文件描述符。

3,父子进程各自给文件加排他锁并sleep10秒,

然后向文件中写入数据。

代码如下

1 /*slock.c*/

2 #include

3 #include

4 #include

5 #include

6 #include

7 #include

8 intmain()9 {10

11 int fd = open( "/dev/shm/test",O_CREAT|O_RDWR,S_IRWXU|S_IRGRP|S_IWGRP|S_IRWXO );12 if ( fd < 0)13 {14 puts( "open error");15 return -1;16 }17 if (fork () == 0) {18 int fd1 = open( "/dev/shm/test",O_RDWR);19 if(flock(fd1,LOCK_EX)==0){20 printf("pid(%d) %s",getpid(), "the file was locked by child .\n");21 puts( "child sleep now ...");22 sleep( 10);23 write(fd, "child\n",strlen("child\n"));24 if(flock(fd1,LOCK_UN)==0){25 puts("child the file was unlocked .\n");26 }27 }28 close( fd1);29 puts( "child exit...");30

31 } else{32 if(flock(fd,LOCK_EX)==0){33 printf("pid(%d) %s",getpid(), "the file was locked by parent .\n");34 puts( "parent sleep now ...");35 sleep( 10);36 write(fd, "parent\n",strlen("parent\n"));37 if(flock(fd,LOCK_UN)==0){38 puts("parent the file was unlocked .\n");39 }40 }41

42 puts( "parent exit...");43 close( fd );44 }45 return 0;46 }

执行结果

[[email protected]]# ./slockc

pid(1516) the file was locked by parent .

parent sleep now ...

parent the file was unlocked .

parent exit...

[[email protected]]# pid(1517) the file was locked  by child .

child sleep now ...

child the file was unlocked .

child exit...

最后查看   /dev/shm/test内容

parent

child

原文:http://www.cnblogs.com/snail88/p/7727236.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值