ตัวอย่าง System Call ที่เรียกผ่าน Library ของภาษา C
#include <stdio.h>int main(void) { printf("hello, world!\n"); //จะไปเรียก systemcall return 0;}ตัวอย่าง 1 - ใช้ได้เฉพาะ Linux อันนี้จะขึ้นอยู่กับระบบปฏิบัติการ unix เพียงอย่างเดียว
#include <unistd.h>int main(void) { write(1, "hello, world!\n", 14); return 0;}ตัวอย่าง 2 - ใช้ได้เฉพาะ Linux อันนี้เป็นการเรียกใช้ system call โดยตรง แต่ข้อเสียคือ number ของ system call ที่เรียกใช้จะขึ้นอยู่กับ OS ที่เป็น unix
#include <unistd.h>#include <sys/syscall.h>int main(void) { syscall(SYS_write, 1, "hello, world!\n", 14); return 0;}ตัวอย่าง 3 - อ่านค่าจาก keyboard
#include <unistd.h>#include <sys/syscall.h>
int main() { char buffer[50]; long bytes;
// Display prompt char *prompt = "Enter your name: "; syscall(SYS_write, 1, prompt, 17);
// Read input bytes = syscall(SYS_read, 0, buffer, 50);
// Display greeting char *greeting = "Hello, "; syscall(SYS_write, 1, greeting, 7);
// Echo name syscall(SYS_write, 1, buffer, bytes);
return 0;}ตัวอย่างที่ 4 - อ่านค่าจาก File
#include <unistd.h>#include <sys/syscall.h>#include <fcntl.h>
int main() { char buffer[100]; char ch; long fd; long bytes; int pos = 0; int line_num = 1;
fd = syscall(SYS_open, "lines.txt", O_RDONLY);
if (fd < 0) { syscall(SYS_write, 2, "Error opening file\n", 19); return 1; }
// Read character by character while ((bytes = syscall(SYS_read, fd, &ch, 1)) > 0) { if (ch == '\n') { // Display line number char num_str[10]; int n = line_num; int digit_pos = 0;
if (n == 0) { num_str[digit_pos++] = '0'; } else { char digits[10]; int dc = 0; while (n > 0) { digits[dc++] = '0' + (n % 10); n /= 10; } for (int i = dc - 1; i >= 0; i--) { num_str[digit_pos++] = digits[i]; } } num_str[digit_pos++] = ':'; num_str[digit_pos++] = ' ';
syscall(SYS_write, 1, num_str, digit_pos); syscall(SYS_write, 1, buffer, pos); syscall(SYS_write, 1, "\n", 1);
pos = 0; line_num++; } else { buffer[pos++] = ch; } }
// Last line (if no newline at end) if (pos > 0) { syscall(SYS_write, 1, buffer, pos); syscall(SYS_write, 1, "\n", 1); }
syscall(SYS_close, fd);
return 0;}ตัวอย่างที่ 6 - เขียนข้อมูลลงไฟล์
#include <unistd.h>#include <sys/syscall.h>#include <fcntl.h>
int main() { long fd;
fd = syscall(SYS_open, "lines.txt", O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd < 0) { syscall(SYS_write, 2, "Cannot create file\n", 19); return 1; }
// Write multiple lines syscall(SYS_write, fd, "Line 1\n", 7); syscall(SYS_write, fd, "Line 2\n", 7); syscall(SYS_write, fd, "Line 3\n", 7);
syscall(SYS_close, fd);
syscall(SYS_write, 1, "Three lines written\n", 20);
return 0;}