How can I make the system call write() print to the screen?

前端 未结 5 1447
故里飘歌
故里飘歌 2021-02-01 22:48

For my OS class I\'m supposed to implement Linux\'s cat using only system calls (no printf)

Reading this reference I found it being used to print to a file. I guess I sh

5条回答
  •  逝去的感伤
    2021-02-01 23:28

    A system call is a service provided by Linux kernel. In C programming, functions are defined in libc which provide a wrapper for many system calls. The function call write() is one of these system calls.

    The first argument passed to write() is the file descriptor to write to. The symbolic constants STDERR_FILENO, STDIN_FILENO, and STDOUT_FILENO are respectively defined to 2, 0, and 1 in unidtd.h. You want to write to either STDOUT_FILENO or STDERR_FILENO.

    const char msg[] = "Hello World!";
    write(STDOUT_FILENO, msg, sizeof(msg)-1);

    You can alternatively use the syscall() function to perform an indirrect system call by specifying the function number defined in syscall.h or unistd.h. Using this method, you can guarantee that you are only using system calls. You may find The Linux System Call Quick Refernence (PDF Link) to be helpful.

    /* 4 is the system call number for write() */
    const char msg[] = "Hello World!";
    syscall(4, STDOUT_FILENO, msg, sizeof(msg)-1);

提交回复
热议问题