【问题标题】:Error message while compiling flock struct C++编译flock struct C++时出现错误消息
【发布时间】:2020-05-17 01:00:34
【问题描述】:

我正在尝试使用 fcntl() 系统调用在文件上创建锁,但为了做到这一点,您需要传入一个 fcntl 结构体的实例,这是一个在 fcntl 中定义的结构体.h 文件。我看过 Youtube 视频,在互联网上搜索解决方案,但我仍然无法弄清楚如何让我的代码无错误地编译。我创建了一个flock struct的实例,如下所示:

#include <fcntl.h>
int start = calculate_buffer(i);
int lock_size = calculate_lock_size(i, j);
int pid = getpid();
struct flock fl{start, lock_size, pid, F_UNLCK, SEEK_SET};

如果您认为问题在于我传递参数的顺序,那不是问题,因为这就是它们为 macOS 排序的方式(我不知道为什么它与 Linux 不同)。无论如何,我尝试使用以下代码编译我的代码:

g++ main.cpp
gcc main.cpp

两者都会产生以下错误:

main.cpp:111:20: error: expected ';' at end of declaration
struct flock fl{start, lock_size, pid, F_UNLCK, SEEK_SET};
               ^
               ;
1 warning and 1 error generated.

为什么会这样?我能做些什么来解决它? 以下是我使用的一些参考资料,表明这正是它的目的:

https://pubs.opengroup.org/onlinepubs/009695399/functions/fcntl.html https://www.youtube.com/watch?v=whYnqxKSBBo&t=339s

【问题讨论】:

    标签: flock fcntl


    【解决方案1】:

    初始化器列表需要在要初始化的变量和列表本身之间有一个等号。您的声明应为:

    struct flock fl = {start, lock_size, pid, F_UNLCK, SEEK_SET};
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-05
      • 2020-11-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-24
      相关资源
      最近更新 更多