Written in front: I communication major sophomore, self-study apue, time is limited, this series is to draw time to write, currently has seen 15 chapters, now from scratch, if there are errors please advise.
First question:
Functions such as write and read are system calls, where there is no buffer without a user buffer, not a kernel buffer, and here in my own opinion, write and read copy the data to the buffer and not directly to the file. But wait for a certain condition to be written in after, but the concrete mechanism still need to study. At the same time, it also exposes a problem, each time I/O is required to make system calls, which is undoubtedly a waste of system resources, so this also for the subsequent standard I/O function library generation made a foreshadowing.
The second question:
First on the code:
#include"apue.h"#include<stdio.h>#include<fcntl.h>intDup2_self (Const intOFD,Const intNFD);intMain () {intFD; intFlag; FD= Open ("Tempfile", O_RDWR | O_creat |O_trunc); Flag= Dup2 (0, FD); Write (FD,"hello\n",6);}intDup2_self (Const intOFD,Const intNFD) { Char*fdptr; intOpenMAX =sysconf (_sc_open_max); intTEMPFD; intCount =0; intFdarr[openmax]; inti; if(Ofd > OpenMAX | | nfd >OpenMAX) {fprintf (stderr,"The arguement error\n"); Exit (1); } fdptr=malloc( -*sizeof(Char)); sprintf (Fdptr,"/proc/%d/fd/%d", Getpid (), OFD); if(Access (FDPTR,0) <0) {fprintf (stderr,"The OFD is not open\n"); Exit (2); } sprintf (Fdptr,"/proc/%d/fd/%d", Getpid (), NFD); if(Access (FDPTR,0) <0) {fprintf (stderr,"The NFD is not open\n"); Exit (3); } if(NFD = =ofd)returnNFD; Close (NFD); while(TEMPFD =DUP (OFD)) { if(TEMPFD = =NFD) Break; ElseFdarr[count++] =TEMPFD; } printf ("%d\n", NFD); for(i =0; I < count; i++) Close (Fdarr [i]); returnNFD;}
This code obviously can not do dup2 atomicity, but in the function of at least to achieve the required functionality, of course, reliability I do not have a lot of verification, this recent implementation let me clear a number of problems: the first--dup2 of the use of the rules, in fact, the file descriptor and file description of the relationship between the flag is removed, Reboot to another file in the description flag. The second--dup use method, it always returns the smallest available file descriptor value, for example here NFD (i print this value on Linux is 3) is close, after the DUP is directly or 3, it can be seen after the close off or the file descriptor is available. Third--How to view the file descriptor opened by a process in/proc/pid/fd/#就可以. The final result is that when I go to the FD write in main, it is displayed in the standard output.
—————————————————————————————————————————————————— Split Line 2016.6.1
Apue Chapter III Some humble opinions on exercises (occasional updates)