System Programming Overview system call system call system call Overview of I / O function system calls and library functions

System Programming Overview

      Operating system functions:

            Operating system to manage all the resources, and associate different devices and different programs

      Linux System Programming:

            In the programming environment Linux operating system and uses a variety of system calls and libraries provided by the operating system, access to system resources

Overview of system calls

     Software-level UNIX-like systems:

      A set of "special" system call function interface provided to a user operating system program
      user interfaces for service program operating system (kernel) provided by the set of
examples:

    The user can invoke the associated system file system, the system requests a file open, file read and write, or close the file

 

   System call by function logic:

        Process control, interprocess communication, file system control, system control, memory management, network management, socket control, user management

   The return value of the system call:
            Success: 0

            Failed: negative

            Error information is stored in the global variable errno, perror function can be used to print an error message

    System call to follow norms

           In Linux, the Application Programming Interface (API) follows the POSIX standard

          POSIX standard was based on existing UNIX practices and experiences, describe the operating system call programming interface (actually API), used
to ensure that the application source code can be ported on a run on multiple operating systems

   Such as:

       Written under linux open, write, read can be ported directly to the unix operating system

System Call I / O functions  

       Function I / O system calls in operation, are for the file descriptor

       By operating a corresponding file descriptor can be directly

    Such as:

           open、 close、 write 、 read、 ioctl

    File descriptor

          Non-negative integer file descriptor

          When you open an existing file or create a new file system (kernel) returns a file descriptor

          File descriptor is used to specify an open file

// 程序运行后这三个文件描述符是默认打开
#define    STDIN_FILENO    0    //标准输入的文件描述符
#define    STDOUT_FILENO   1    //标准输出的文件描述符
#define    STDERR_FILENO   2    //标准错误的文件描述符

    open function

         Open a file

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

// 文件存在
int open(const char *pathname, int flags);

/* 文件不存在
 * pathname: 文件的路径及文件名
 * flags:行为标志
 *       O_RDONLY  只读方式打开
 *       O_WRONLY  只写方式打开
 *       O_RDWR    可读可写方式打开
 *  下列值 位或
 *       O_CREAT     文件不存在则创建文件,mode说明文件权限
 *       O_EXCL      指定O_CREAT,且文件已存在 则出错
 *       O_TRUNC     文件存在 清除文件内容
 *       O_APPEND    写文件,数据添加到文件末尾
 *       O_NONBLOCK  打开的文件是FIFO,字符文件,块文件,该选项为非堵塞标志位
 * mode:文件权限(可读,可写,可执行)的设置
 *       取值       八进制      含义
 *       S_IRWXU    700       文件所有者的读,写,可执行权限
 *       S_IRUSR    400       文件所有者的读权限
 *       S_IWUSR    200       文件所有者的写权限
 *       S_IXUSR    100       文件所有者的可执行权限
 *       S_IRWXG    70        文件所有者同组用户的读写可执行权限
 *       S_IRGRP    40        文件所有者同组用户的读权限
 *       
 * return:成功:文件描述符 失败:-1,可用 perror 查看原因
 */
int open(const char *pathname, int flags, mode_t mode);

    close function

       Close a file

#include <unistd.h>

/*
 *fd:调用open打开文件返回的文件描述符
 * return:成功:0 失败:-1 可用 perror 去查看原因
 */
int close(int fd);

    write function

        Specifies the number of data written to a file

#include <unistd.h>

/*
 * fd:文件描述符
 * addr:数据首地址
 * count: 写入数据的字节个数
 * return:成功:写入字节个数 失败:-1
 */
ssize_t write(int fd, const void *addr, size_t count);

    read function

         Data memory to read the specified number of

#include <unistd.h>

/*
 * fd:文件描述符
 * addr:内存首地址
 * count:读取的字节个数
 * return:成功:读取的字节个数  失败:-1
 */
ssize_t read(int fd, void *addr, size_t count);

    remove library functions

        Delete Files

#include <stdio.h>

/*
 * pathname: 文件路径+文件名
 * return:成功:0 失败:-1
 */
int remove(const char * pathname);

 example:

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void test1();
void test2();
void test3();

int main(int argc, char *argv[])
{
    test1();
    test2();
    test3();
    return 0;
}

void test1()
{
    char buf[32] = "";

    read(0, buf, sizeof(buf));
    write(1, buf, strlen(buf));
}

void test2()
{
    int fd = 0;
    char str[] = "hello file";

    fd = open("./a.txt",O_WRONLY | O_CREAT | O_EXCL, 0777);
    
    if(-1 == fd)
    {
        perror("open");
        return;
    }

    printf("fd = %d\n", fd);
    write(fd, str, strlen(str));

    close(fd);
}

void test3()
{
    int fd = 0;
    char buf[128] = "";
    int len = 0;

    fd = open("a.txt",O_RDONLY);
    if(-1 == fd)
    {
        perror("open");
        return;
    }
    
    len = read(fd, buf, sizeof(buf));
    printf("len = %d\n", len);
    printf("buf = %s\n", buf);
    
    close(fd);
}

 print:

 

System calls and library functions

      No need to call the system call

              Without switching to kernel space to complete the function of all the functions, and the result is fed back to the application program

              Such as: strcpy, bzero string manipulation functions, etc.

     You need to call the system call

              Need to switch to kernel space, such a packaging system function calls to corresponding function

              Such as printf, fread, etc.

    The relationship between library functions and system calls

           Not all system calls are packaged in a library function, the system provides many of the functions must be implemented to the system by calling

        System call takes time, frequently used programs will reduce the efficiency of the system calls the program

       When running kernel code, CPU work in kernel mode, the system call occurs before the need to preserve the environment stack and memory user mode, and then transferred to the kernel
-state operation

       After the system calls, but also to exchange user state cut. This switching environment will consume a lot of time

       Time library functions to access files as needed, set up different types of buffers, thus reducing the number of direct calls to IO system calls, improve access
efficiency

        Process application calls printf function, the function performed

     Achieve cp command

          Goal:
                Use system call cp command

         Principle:
              call open with the system to open the file, read data from a file using the read, write write data to a file using
              the number of arguments passed to the executable program stored in the argc main function, the parameters stored in the first address array of pointers in argv

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char const * argv[])
{
    int srcFd = 0;
    char fileName[64] = "";
    int dstFd = 0;
    char buf[128] = "";
    int len = 0;

    if(3 != argc)
    {
        printf("请按 ./a.out srcdst 传参\n");
        return 0;
    }

    // 打开源文件
    srcFd = open(argv[1], O_RDONLY);
    if(-1 == srcFd)
    {
        perror("open");
        return 0;
    }

    // 打开目的文件
    sprintf(fileName, "%s/%s",argv[2],argv[1]);
    dstFd = open(fileName, O_WRONLY | O_CREAT, 0777);
    if(-1 == dstFd)
    {
        perror("open");
        return 0;
    }

    while(1)
    {
        len = read(srcFd, buf, sizeof(buf));
        if(len <= 0)
        {
            break;
        }
        write(dstFd, buf, len);
    }

    close(srcFd);
    close(dstFd);
    return 0;
}

 

 

Published 68 original articles · won praise 10 · views 9896

Guess you like

Origin blog.csdn.net/qq_44226094/article/details/104929533