预览加载中,请您耐心等待几秒...
在线预览结束,喜欢就下载吧,查找使用更方便
如果您无法下载资料,请参考说明:
1、部分资料下载需要金币,请确保您的账户上有足够的金币
2、已购买过的文档,再次下载不重复扣费
3、资料包下载后请先用软件解压,在使用对应软件打开
《Linux操作系统及其应用编程》实验报告班级:10级计科(2)班姓名:学号:时间:2013-6-3地点:综合楼一楼机房实验成绩:优秀□良好□中□及格□不及格□实验题目:两个进程同时操作一个文件实验名称两个进程同时操作一个文件实验目的1、了解并掌握文件控制系统函数fcntl()2、掌握纪录锁的使用实验准备VMwareworkstation8rhel-5.2-server-i386-dvd镜像实验步骤打开计算机并运行Linux系统在文本编辑器中编写程序实验主要代码如下:/*lock_set函数*/voidlock_set(intfd,inttype){structflocklock;lock.l_whence=SEEK_END;/*从文件尾开始*/lock.l_start=0;lock.l_len=0;while(1){lock.l_type=type;/*根据不同的type值给文件上锁或解锁*/if((fcntl(fd,F_SETLK,&lock))==0){if(lock.l_type==F_RDLCK)printf("readlocksetby%d\n",getpid());elseif(lock.l_type==F_WRLCK)printf("writelocksetby%d\n",getpid());elseif(lock.l_type==F_UNLCK)printf("releaselockby%d\n",getpid());return;}/*判断文件是否可以上锁*/fcntl(fd,F_GETLK,&lock);/*判断文件不能上锁的原因*/if(lock.l_type!=F_UNLCK){if(lock.l_type==F_RDLCK)printf("readlockalreadyby%d\n",lock.l_pid);elseif(lock.l_type==F_WRLCK)printf("writelockalreadyby%d\n",lock.l_pid);}}}intmain(void){intfd;if((fd=creat("hello.txt",smode))==-1){perror("Can'tcreatefilehello.txt");exit(1);}elseprintf("createhello.txtok!\n");/*fork()之前打开文件,父子进程共用fd*/if((fd=open("hello.txt",rwmode))==-1){perror("Can'topenfilehello.txt");exit(0);}elseprintf("openhello.txtok!\n");intpid;printf("Systemcallingfork()willstart.\n");pid=fork();if(pid>0){printf("Thisischildprocess!\n");lock_set(fd,F_WRLCK);char*buffer="Thisischildprocesswrite!";if(write(fd,buffer,30)==-1)printf("Writefileerror!\n");elseprintf("Childprocesswriteok!\n");//getchar();lock_set(fd,F_UNLCK);exit(1);/*子进程退出*/}elseif(pid==0){printf("Thisisparentprocess!\n");lock_set(fd,F_WRLCK);char*buffer="Thisisparentprocesswrite!";if(write(fd,buffer,30)==-1)printf("Writefileerror!\n");elseprintf("Parentprocesswriteok!\n");lock_set(fd,F_UNLCK);}if(close(fd)<0)/*在父进程中关闭文件*/{perror("close:");exit(1);}printf("