#include <sys/uio.h>
ssize_t readv(int fd, const struct iovec *iov, int iovcnt);
unix高级环境编程中的定义:
【ssize_t readv(int filedes,const struct iovec iov[ ],int iovcnt) ;
ssize_t writev(int filedes,const struct iovec iov[ ],int iovcnt) ; 】
----------------------------------------------------------------------------
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <fcntl.h>
5 #include <sys/uio.h>
6 #include <unistd.h>
7
8 int main()
9 {
10 struct iovec iov[2];
11 char buf[12],str[12];
12 int fd = open("1.txt",O_RDONLY);
13 if(fd == -1)
14 return -1;
15 iov[0].iov_base = buf;
16 iov[0].iov_len = 12;
17 iov[1].iov_base = str;
18 iov[1].iov_len = 12;
19 int n = readv(fd, iov, 2);
20 printf("n:%d\n", n);
21 //printf("buf:%s\n",buf);
22 //printf("str:%s\n",str);
23 puts(buf);
24 puts(str);
25 close(fd);
26 return 0;
27 }
----------------------------------------------------------------------------
运行结果很奇怪:第一个缓冲区溢出了
tarena@ubuntu:~/mon$ ./a.out
n:23
buf:aaaaaaaaaaaabbbbbbbbbb
str:bbbbbbbbbb
----------------------------------------------------------------------------
ssize_t writev(int fd, const struct iovec *iov, int iovcnt);
----------------------------------------------------------------------------
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <sys/stat.h>
4 #include <fcntl.h>
5 #include <sys/uio.h>
6 #include <unistd.h>
7 #include <string.h>
8 int main()
9 {
10 struct iovec iov[2];
11 char buf[12] = "hello,lyy",str[12] = "nihao,lyy";
12 int fd = open("2.txt",O_WRONLY | O_CREAT);
13 if(fd == -1)
14 return -1;
15 iov[0].iov_base = buf;
16 iov[0].iov_len = strlen(buf);
17 iov[1].iov_base = str;
18 iov[1].iov_len = strlen(str);
19 int n = writev(fd, iov, 2);
20 printf("n:%d\n", n);
21 close(fd);
22 return 0;
23 }
----------------------------------------------------------------------------
运行结果正确,但是为什么需要超级用户才能查看呢?
tarena@ubuntu:~/mon$ sudo cat 2.txt
hello,lyynihao,lyytarena@ubuntu:~/mon$
----------------------------------------------------------------------------
----------------------------------------------------------------------------
ssize_t preadv(int fd, const struct iovec *iov, int iovcnt, off_t offset);
ssize_t pwritev(int fd, const struct iovec *iov, int iovcnt, off_t offset);
ssize_t preadv2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags);
ssize_t pwritev2(int fd, const struct iovec *iov, int iovcnt, off_t offset, int flags);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
preadv(), pwritev():
Since glibc 2.19:
_DEFAULT_SOURCE
Glibc 2.19 and earlier:
_BSD_SOURCE
原文:https://www.cnblogs.com/xpylovely/p/11008693.html