在linux下調用syscalls.h標頭檔

來源:互聯網
上載者:User

 終於開始看 The C 的第八章 The UNIX System Interface 了!這是比較激動人心的一章,學過之後就可以開始寫 Unix 程式了,比如列印目錄,查看檔案大小、檔案屬性等,也就是說可以寫一些比較實用的小程式了。而且一些系統函數,例如 read(),write()等,是 unix 編程的基礎。另外,也講解了 malloc 的一種實現方法,我想這將會加深我對記憶體的理解。

然而,第一個例子就讓我傻眼了。

#include "syscalls.h"

main()
{
  char buf[BUFSIZ];
  int n;

  while ((n = read(0, buf, BUFSIZ)) > 0)
    write(1, buf, n);
  return 0;
}

編譯時間出錯

k@bian:~$ gcc -Wall test.c
test.c:1:22: syscalls.h: No such file or directory
test.c:5: error: `BUFSIZ' undeclared (first use in this function)
test.c:8: warning: implicit declaration of function `read'
test.c:9: warning: implicit declaration of function `write'

書上說 read()和write(),還有BUFSIZ都是 syscalls.h 裡定義的。

我開啟 /usr/include/ 一看,沒有syscalls.h !不過有一個 syscall.h,換上這個還是提示錯誤。

Linux畢竟不是Unix,我當時就有點害怕這一章學不下去。這種時候,當然要google!

沒有直接查到解決辦法,卻知道了可以用man來查

man read

哈哈,有了!赫然寫著

       #include <unistd.h>

       ssize_t read(int fd, void *buf, size_t count);

但是還有問題

k@bian:~$ gcc -Wall test.c
test.c:5: error: `BUFSIZ' undeclared (first use in this function)

這時我突然想到一個辦法,用 grep !

k@bian:~$ grep BUFSIZ /usr/include/*
/usr/include/_G_config.h:#define _G_BUFSIZ 8192
/usr/include/libio.h:#define _IO_BUFSIZ _G_BUFSIZ
/usr/include/stdio.h:#ifndef BUFSIZ
/usr/include/stdio.h:# define BUFSIZ _IO_BUFSIZ
/usr/include/stdio.h:   Else make it use buffer BUF, of size BUFSIZ.  */

原來在stdio.h裡!

程式改成這樣,問題解決

#include <stdio.h>
#include <unistd.h>

main()
{
  char buf[BUFSIZ];
  int n;

  while ((n = read(0, buf, BUFSIZ)) > 0)
    write(1, buf, n);
  return 0;
}

好!可以往下學了:D

還找到這個,在Linux下編程肯定有用的 The GNU C Library Manual。有幾種格式提供下載,建議下載formatted in HTML (976K gzipped tar file) with one web page per node.

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.