Date: Thu, 22 Aug 2019 16:24:19 +0000 From: "Farhan Khan" <farhan@farhan.codes> To: freebsd-hackers@freebsd.org Subject: Trouble using and understanding funopen(3) Message-ID: <519c2fce85fe0db1cd189d2060f09a0f@farhan.codes>
next in thread | raw e-mail | index | archive | help
Hi all,=0A=0AI am having trouble understanding how funopen(3)'s read func=
tion works. Specifically, how do I have the readfn return with less than =
the requested amount of bytes.=0A=0AMy understanding: I believe that funo=
pen(3) allows you to assign the read, write and close methods to a FILE s=
tream. When a program runs fread(3) on a FILE stream opened by funopen(3)=
, the program will run the readfn handler in a loop until it returns eith=
er returns the requested number of bytes, 0 or -1 (error).=0A=0AQuestion:=
How do I structure the code so that readfn returns with less than the nu=
mbe of requested bytes? For example, what if the calling fread() function=
requests 100 bytes, but the readfn can only return 10 bytes? What mechan=
ism do I need to implement so that the fread(3) returns "10" bytes rather=
than the readfn handler running 10 times? This results in the fread()'s =
return value as 100, even though only 10 bytes were *actually* read.=0A=
=0AI have looked at a few examples from the src tree. Clearly they have t=
o use buffering and append the bytes they read to the memory object they =
were initially passed. Somehow they return with the number of bytes they =
actually read, not necessarily the requested amount. But it is not clear =
to me how they make this distinction and avoid having their respective re=
adfn function re-rerun. Also, in the examples I did look up there does no=
t appear to be any use of setvbuf().=0A=0ABelow is a very simple test cas=
e to illustrate the issue.=0A=0A------=0A#include <stdio.h>=0A#include <s=
tring.h>=0A#include <stdlib.h>=0A=0Astatic int=0Assh_readfn(void *v, char=
*buf, int len)=0A{=0A printf("Running readfn handler\n");=0A memcpy(buf,=
"AAAAAAAAAA", 10);=0A return 10;=0A}=0A=0Astatic int=0Assh_writefn(void =
*v, const char *buf, int len)=0A{=0A return 0;=0A}=0A=0Aint=0Amain()=0A{=
=0A int x;=0A char buf[1000];=0A FILE *f;=0A=0A f =3D funopen(NULL, ssh_r=
eadfn, ssh_writefn, NULL, NULL);=0A if (f =3D=3D NULL) {=0A printf("funo=
pen failed, exiting.\n");=0A exit(0);=0A }=0A=0A x =3D fread(buf, 1, 100=
, f);=0A printf("Bytes read: %d\n", x);=0A}=0A------=0A=0AThis displays 1=
0 "Running readfn handler" lines fllowed by "Bytes read: 100" even though=
I am explicitly returning 10 in ssh_readfn. Please advise what the mecha=
nism is only return with less than the requested number of bytes.=0A=0ATh=
anks!=0A---=0AFarhan Khan=0APGP Fingerprint: 1312 89CE 663E 1EB2 179C 1C8=
3 C41D 2281 F8DA C0DE
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?519c2fce85fe0db1cd189d2060f09a0f>
