Linux C 一些函數 所屬的頭文件 2011-03-07 10:25:07
分類: LINUX
在編寫程序時,有時總是不記得所使用的函數在哪個庫函數中。現在先把自己以前經常用到的函數頭文件總結一下。 有不對的地方還請指教。
1,系統調用 文件的操作函數
#inlclude <fcntl.h>
int open(char *name,int how) 第二個參數,O_RDONLY O_WRONLY O_RDWR O_CREAT
#include <unistd.h>
int close(int fd)
size_t read(int fd,void *buf, size_t count)
size_t write(int fd,const void *buf,size_t count)
sleep(1) 系統睡眠一秒鐘,最小單位為一秒。
#define msleep(x) usleep(x*1000)
msleep(500); 系統睡眠0.5秒
#include <stdio.h>
perror("會出現錯誤的函數名")
#include <string.h>
char *strerror(int errnum) 依據錯誤代碼errnum來查找錯誤原因字符串
char *strcpy(char *dest,const char *src)
int strcmp(char *s1,const char *s2) s1若等于s2的值則返回0值
int strncmp(char *s1,const char *s2,int n) 前n個字符串比較
2,進程控制函數
#include <unistd.h>
pid_t fork(void) 子進程中返回0 父進程中返回子進程ID 出錯返回-1
pid_t getpid(void) pid_t getppid(void)
pid_t vfork(void)
exec函數族
進程pid 的類型為pid_t 類型,它包含于#include <sys/types.h> 若定義一個進程pid變量,則需要包含此頭文件
exit(n)結束進程 父進程可以由wait函數來獲得子進程結束裝狀態。
在進程結束的時候,會關閉文件描述符號,做一些清理工作,只保留進程返回狀態等信息
調用exit(),子進程會關閉所有打開的進程描述符 exit會作清理工作,比如說,釋放內存(在C++里面會主動的調用析構函數,),關閉文件句柄的工作,包括刷新IO流。
_exit(n)直接退出,不會做一些清理工作,也不會關閉文件描述符。
#include <sys/wait.h>
pid_t wait(int *status) 等待任意子進程結束。子進程結束狀態值由status返回。
如WEXITSTATUS(status) 可以獲得exit(2)中返回的值,status=2,這樣就可以知道所等待的為哪個進程。如果不用這個宏轉換,則status=512.
pid_t waitpid(pid_t pid,int status,int options) 可以指定等待某個進程號pid的進程結束
在使用 waitpid函數時還用到了pid參數,所以還要加上#include <sys/types.h>
關于進程等待函數還有很多宏將status轉換為需要的值,需要了解。
3,進程間通信-管道
#include <unistd.h>
int pipe(int filedes[2])
4,進程間通信-命名管道
#include <sys/types.h> #include <sys/stat.h>
int mkfifo(const char *pathname,mode_t mode)
對于命名管道的操作同普通文件的操作
5,消息隊列
數據類型key_t是在頭文件sys/types.h中定義的,它是一個長整形的數據。
key=ftok(".",'A') #include <sys/types.h> #include <sys/ipc.h>
所屬頭文件:#include<sys/types.h> #include <sys/ipc.h> #include <sys/msg.h>
int msgid;
msgid=msgget(k