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

感情迁移 提交于 2019-12-02 20:49:48

Write to the file descriptor for standard output or standard error (1 and 2 respectively).

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);
#include <unistd.h>
/* ... */
const char msg[] = "Hello world";
write( STDOUT_FILENO, msg, sizeof( msg ) - 1 );

First argument is the file descriptor for STDOUT (usually 1), the second is the buffer to write from, third is the size of the text in the buffer (-1 is to not print zero terminator).

#define _GNU_SOURCE         /* See feature_test_macros(7) */    
#include <unistd.h> // For open, close, read, write, fsync
#include <sys/syscall.h>  //For SYSCALL id __NR_xxx

//Method 1 : API    
write(1,"Writing via API\n",\
        strlen("Writing via API\n") ); 
fsync(1);
//Method 2  : Via syscall id
const char msg[] = "Hello World! via Syscall\n";
syscall(__NR_write, STDOUT_FILENO, msg, sizeof(msg)-1);     
syscall(__NR_fsync, STDOUT_FILENO );    // fsync(STDOUT_FILENO);

Your reference is incorrect. It's part of C++ and has nothing to do with your assignment. The correct reference is http://www.opengroup.org/onlinepubs/9699919799/functions/write.html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!