【问题标题】:fnctl : invalid argument in Cfcntl : C 中的无效参数
【发布时间】:2013-01-16 09:59:11
【问题描述】:

我正在处理进程间通信中的文件锁定, 以下代码使我感到困惑... 在 Macintosh 中通过终端运行时

    #include <stdio.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <fcntl.h>
    #include <unistd.h>

  int main(int argc , char *argv[])
  {
   // l_type , l_whence , l_start , l_len , l_pid
    struct flock f1 = {F_WRLCK , SEEK_SET , 0 , 0 , 0};
    int fd;

  f1.l_pid = getpid() ;

// if command line arguments  , then assign a Read Lock
if (argc > 1)
{
    f1.l_type = F_RDLCK ;
}

if ((fd = open("lockdemo.c", O_RDWR)) == -1)
{
    perror("open");
    exit(1);
}

printf("Press <RETURN> to try to get lock");
getchar() ;

printf("trying to get lock...");

if (fcntl(fd, F_SETLKW , &f1)  == -1)
{
    perror("fcntl");
    exit(1);
}


printf("got lock !\n");
printf("Press <RETURN> to release lock:");
getchar();

f1.l_type = F_UNLCK ; //set to unlock same region

if (fcntl(fd, F_SETLK , &f1) == -1)
{
    perror("fcntl");
    exit(1);
}

printf("Unlocked .. \n");
close(fd);

return 0;
 }

但出现以下错误: fnctl : 无效参数

请帮助我解决这个问题...

【问题讨论】:

  • 哪个 fcntl 调用会导致错误?
  • “试图获得块”之后的那个
  • 先生,您有 gud 声望点...请您为 C 程序员创建一个聊天室...已经有一个房间 ..但不活动...和 ​​ 不允许我提问......所以 PLZ 先生......

标签: c file-locking inter-process-communicat


【解决方案1】:

在 MacO 上,struct flock 的成员的顺序与 Linux 中不同。

为了使您的代码可移植,您应该按名称分配字段,而不是假定特定的顺序。

来自 fcntl 的 MacOS 手册页:

         struct flock {
             off_t       l_start;    /* starting offset */
             off_t       l_len;      /* len = 0 means until end of file */
             pid_t       l_pid;      /* lock owner */
             short       l_type;     /* lock type: read/write, etc. */
             short       l_whence;   /* type of l_start */
         };

【讨论】:

  • 这是一个非常有效的观点,可能是 OP 面临问题的原因。 +1
  • 是的先生....谢谢你!!!!!它起作用了...它正确显示了文件锁定以及等待锁定... :) 谢谢!!!!
【解决方案2】:

我试过你的代码,它在 Linux Min 12 64 位上没有任何修改就可以正常工作。

 gcc lock.c 
-Compaq-6200-Pro-MT-PC ~/Dropbox/Misc $ ./a.out 1
Press <RETURN> to try to get lock
trying to get lock...got lock !
Press <RETURN> to release lock:
Unlocked .. 
-Compaq-6200-Pro-MT-PC ~/Dropbox/Misc $ ./a.out
Press <RETURN> to try to get lock
trying to get lock...got lock !
Press <RETURN> to release lock:
Unlocked .. 

当然,我在同一个文件夹中创建了一个 lockdemo.c 文件。

好像你在 mac 上的锁定 api 可能有问题。

【讨论】:

  • 根据程序,如果不传递参数,文件应该得到WRITE LOCK...但是如果不传递参数,则显示上述错误
  • 您对文件 lockdemo.c 有写权限吗?自己在本地创建以确保
  • 查看@Klas Lindbäck 发布的解决方案。这很可能是您的错误的原因。
  • 以此为教训,始终按名称填写结构字段。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多