如何解决像猫一样健壮高效的C实现
我想学习实现类似 cat 的函数,它只是从文件中获取输入并打印到标准输出。
但我不确定 write()
的行在所有情况下都是健壮的,因为它可能写的少于 n
。但是我无法创建测试用例来实现这种情况。如何制作一个测试用例,以便它可以导致少于 n 个字符被写入?另外,如何相应地修改代码以使程序健壮(对于这种情况,以及我没有描述的其他情况)?
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main(int argc,char *argv[]) {
const char *pathname = argv[1];
int fd;
if((fd = open(pathname,O_RDONLY)) == -1) {
perror("open");
return 1;
}
#define BUF_SIZE 1024
char buf[BUF_SIZE];
ssize_t n;
while((n = read(fd,&buf,BUF_SIZE)) > 0) {
if(write(STDOUT_FILENO,n) == -1) {
perror("write");
return 1;
}
}
if(n == -1) {
perror("read");
return 1;
}
if(close(fd) == -1) {
perror("close");
return 1;
}
return 0;
}
编辑:我根据 Armali 提到的管道阻塞测试用例修复了之前代码中的 write()
错误。有人可以检查是否还有其他错误吗?
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
int main(int argc,O_RDONLY)) == -1) {
perror("open");
return 1;
}
#define BUF_SIZE 2*65536
char buf[BUF_SIZE];
ssize_t r_n;
while((r_n = read(fd,BUF_SIZE)) > 0) {
ssize_t w_n;
int i = 0;
while((w_n = write(STDOUT_FILENO,buf+i,r_n)) < r_n) {
if(w_n == -1) {
perror("write");
return 1;
}
r_n -= w_n;
i += w_n;
}
}
if(r_n == -1) {
perror("read");
return 1;
}
if(close(fd) == -1) {
perror("close");
return 1;
}
return 0;
}
解决方法
如何制作一个测试用例,使得它可以写入少于 n 个字符?
根据系统,这并不难。 man 2 write
告诉:
… partial writes can occur for various reasons; for example,because there was
insufficient space on the disk device to write all of the requested bytes,or because
a blocked write() to a socket,pipe,or similar was interrupted by a signal …
让我们关注管道写入,如果管道缓冲区已满则阻塞。此示例针对 Linux;其他系统上的数字可能会有所不同。 man 7 pipe
讲述了管道容量:
Since Linux 2.6.11,the pipe capacity is 16 pages (i.e.,65,536 bytes in a system with
a page size of 4096 bytes).
为了测试用例而使用它,我们必须将您的 BUF_SIZE
增加到更大的值,例如 1024*128
。然后我们就可以进行实验了:
~$ dd count=256 </dev/zero >zeros
256+0 records in
256+0 records out
131072 bytes (131 kB,128 KiB) copied,0.00357324 s,36.7 MB/s
~$ strace -ewrite ./a.out zeros|(sleep 9; dd)
write(1,"\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"...,131072^Z
[1]+ Stopped strace -ewrite ./a.out zeros | ( sleep 9; dd )
~$ fg
strace -ewrite ./a.out zeros | ( sleep 9; dd )
) = 65536
--- SIGCONT {si_signo=SIGCONT,si_code=SI_USER,si_pid=482,si_uid=2001} ---
+++ exited with 0 +++
128+0 records in
128+0 records out
65536 bytes (66 kB,64 KiB) copied,0.00546081 s,12.0 MB/s
- 首先我们准备一个 128 KiB 的文件。
- 然后我们用
strace -ewrite
运行程序,看看写操作;我们将其输出通过管道传输到(sleep 9; dd)
以延迟读取。在此延迟期间,我们按 Ctrl-Z 发出 STOP 信号。 - 最后,我们使用
fg
继续该程序。现在我们看到使用 count131072
调用的写入操作仅返回写入的65536
个字节。
另外,如何相应地修改代码以使程序健壮(对于这种情况,以及我没有描述的其他情况)?
对于本案和类似案件,您可以按照 David C. Rankin 写道:
在那里您将循环直到写入 n
个字节,以跟踪每次调用时写入的数字。
除了检查所有被调用的库函数的返回值之外,我不能说如何使程序在未描述的情况下健壮。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。