下面是源码,我的疑问在源码里已经标出来了
运行的时候,把这个源文件编译,然后打开两个终端,在这两个终端里运行这个程序,对于加与不加printf()的疑问,加和不加运行结果不一样????为什么呢???跪求。。。。。。
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
void lock_set(int fd,int cmd)
{
struct flock lock;
lock.l_type=cmd;
lock.l_start=0;
lock.l_whence=SEEK_SET;
lock.l_len=0;
lock.l_pid=-1;
fcntl(fd,F_GETLK,&lock);
if(lock.l_type!=F_UNLCK)
{
if(lock.l_type==F_WRLCK)
printf("the file is alreadly seted by %d F_WRCLK",lock.l_pid);
else if(lock.l_type==F_RDLCK)
printf("the file is alreadly seted by %d F_RDCLK",lock.l_pid);
}
printf("\n"); //这是我的疑问点,就是如果这里不加printf()的话,运行的结果和加printf()的结果为什么不一样呢?这是什么原因
lock.l_type=cmd;
if(fcntl(fd,F_SETLKW,&lock)<0)
{
printf("clok err\n");
exit(0);
}
switch(lock.l_type)
{
case F_WRLCK :
printf("wrlock is set by %d\n",getpid());
break;
case F_RDLCK :
printf("RDlock is set by %d\n",getpid());
break;
case F_UNLCK :
printf("UNlock is set by %d\n",getpid());
break;
default :
break;
}
}
int main()
{
int fd;
fd=open("chenyu.dat",O_CREAT|O_RDWR,0644);
if(fd<0)
{
printf("open err\n");
exit(0);
}
lock_set(fd,F_WRLCK);
getchar();
lock_set(fd,F_UNLCK);
getchar();
close(fd);
return 0;
}