Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
137 views
in Technique[技术] by (71.8m points)

c - Confused with read() system call

I am very confused with read() calls to get inotify events.

Here is the code:

#define EVENT_SIZE sizeof(inotify_event)
int fd = inotify_init();
int wd = inotify_add_watch(fd, dir, IN_MODIFY);
void* p = malloc(sizeof(EVENT_SIZE));
read(wd, p, (EVENT_SIZE + 10));

My test file is a.txt. The output after debug in gdb is:

{wd = 0, mask = 0, cookie = 0, len = 0, name = 0x558f05d002d0 ""}

Now, when I change the last line to read(fd, p, (EVENT_SIZE + 16));, the output that I get in gdb is:

{wd = 1, mask = 2, cookie = 0, len = 16, name = 0x5625cdd422d0 ".a.txt.swp"}

Q1. Why don't I get an overflow error because in both cases, I am writing more than the allocated buffer p?

Q2. If there is no error, then my first program should also work because my filename is less than 10, but it doesn't work and it only works with 16. What am I missing here?

compiler - g++ 9.3.0

os - ubuntu 20.04

Thank you.

question from:https://stackoverflow.com/questions/65860234/confused-with-read-system-call

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  1. The behaviour of writing outside the boundaries of an array is undefined. Additionally, read reads up to the given number of bytes.
  2. ???

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...