[Linux system programming] 12. Comparison of system calls and library functions

Table of contents

system call

the code

Library Functions

the code

system call

 

        The program setting is 10, so the program runs at a maximum of 10, which is particularly time-consuming when writing large files. Because the program writes data directly into the kernel from buf , this process is the most time-consuming, and then needs to return from the kernel to buf .

 

the code

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>

int main(int argc,char *argv[]){
    char buf[1024];
    int n=0;
    int fp1=open(argv[1],O_RDONLY);
    if(fp1==-1){
        perror("fp1 error");
        exit(1);
    }
    int fp2=open(argv[2],O_RDWR|O_CREAT|O_TRUNC,0664);
    if(fp2==-1){
        perror("fp2 error");
        exit(1);
    }
    while((n=read(fp1,buf,10))!=0){
        if(n<0){
            perror("read error");
            break;
        }
        write(fp2,buf,n);
    }
    close(fp1);
    close(fp2);
    return 0;
}

Library Functions

        The library function is written 4096 at a time. First store the data of buf in the blue buffer area , store 4096 bytes and then write it into the kernel at one time , so in some cases, library functions are better than system calls.

 

the code

#include <stdio.h>
#include <stdlib.h>
int main(void){
    FILE *fp,*fp_out;
    int n;
    fp = fopen("a1.txt","r");
    if(fp == NULL){
        perror("fopen error");
        exit(1);
    }
    fp_out = fopen("a3.txt","w" );
    if(fp_out == NULL){
        perror("fopen error");
        exit(1);
    }
    while((n = fgetc(fp)) != EOF){
        fputc(n,fp_out);
    }
    fclose(fp);
    fclose(fp_out);
    return 0;
}

Guess you like

Origin blog.csdn.net/CETET/article/details/130063783