Linux核心中進行系統調用

來源:互聯網
上載者:User
基本參考newsmth的Kernel Tech版的那個FAQ就可以,準則如下:

4.2 在核心中可以使用系統調用嗎?
   a. 可以。核心原始碼中就有使用系統調用的例子,如open()、execve()等。
   b. 在核心中使用系統調用必須要在源檔案中包括以下兩行:
      #define __KERNEL_SYSCALLS__
      #include <linux/unistd.h>
   c. 核心中使用系統調用的相關定義可查看檔案include/asm/unistd.h。
      如果要用的系統調用該檔案中沒有定義,可以按照其格式自行添加。
   d. 如果要在模組中使用系統調用,必須要自己定義errno如:
      int errno;
      核心在lib/errno.c中定義了errno,但該符號不匯出,所以模組編程時需要自己
      定義errno,用以存放系統調用出錯號。

但是對於我這樣的菜菜,還是有點不夠詳細,自己實踐了一下,於是在下邊給個執行個體出來,希望能給和我一樣的新手們一些協助:(展示了調用getpid()和stat())

#define __KERNEL_SYSCALLS__
#include <linux/unistd.h>
#include <linux/stat.h> // other needed header
int errno // if needed

//

unsigned int getsockcnt(void)
{
    _syscall0(int, getpid) //must needed
    _syscall2(int, stat, const char *, file_name, struct stat *, buf) //must needed

    unsigned int n = 0;
    pid_t pid = getpid(); // systemcall
    char path[256];
    sprintf(path, "/proc/%d/fd", pid);
    int i = 0;
    for (; i < 1024; i++) 
    {
        sprintf(path, "/proc/%d/fd/%d", pid, i);
        struct stat st;
        if (stat(path, &st) == 0) // system call
            if (S_ISSOCK(st.st_mode))
                n++;
    }

    return n;
}

//  call this function

主要注意那個_syscallX的macro就可以了,這個newsmth的FAQ中沒說。

btw:
突然發現自己今天寫了3篇blog了,._.Y
同時發現編譯核心是CPU密集型操作,而不是I/O密集型,因為編譯的時候CPU風扇狂轉,嗡嗡的,而硬碟聲幾乎沒變,呵呵。
決定把自己blog的名稱改回AAOP了,其意自明~

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.