unistd.h是unix std的意思,是POSIX標準定義的unix類系統定義符號常量的頭文件,
包含了許多UNIX系統服務的函數原型
unistd.h在unix中類似於window中的windows.h
#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
許多在Linux下開發的C程序都需要頭文件unistd.h,但VC中沒有個頭文件,
所以用VC編譯總是報錯。把下面的內容保存爲unistd.h,可以解決這個問題。
/** This file is part of the Mingw32 package.
* unistd.h maps (roughly) to io.h
*/
#ifndef _UNISTD_H
#define _UNISTD_H
#include <io.h>
#include <process.h>
#endif /* _UNISTD_H */
unistd.h含有的常量與函數:
ssize_t read(int, void *, size_t); // 讀取文件使用
int unlink(const char *);
ssize_t write(int, const void *, size_t); // 寫文件
int usleep(useconds_t); // 進程休眠,單位爲微妙
unsigned sleep(unsigned); // 進程休眠,單位爲秒
int access(const char *, int); // 獲取文件的權限
unsigned alarm(unsigned);
int chdir(const char *);
int chown(const char *, uid_t, gid_t);
int close(int); // 關閉文件
size_t confstr(int, char *, size_t);
void _exit(int);
pid_t fork(void);
NULL // Null pointer
SEEK_CUR // Set file offset to current plus offset.
SEEK_END // Set file offset to EOF plus offset.
SEEK_SET // Set file offset to offset.
在進行堵塞式系統調用時,爲避免進程陷入無限期的等待,能夠爲這些堵塞式系統調用設置定時器。Linux提供了alarm系統調用和SIGALRM信號實現這個功能。
要使用定時器,首先要安裝SIGALRM信號。假設不安裝SIGALRM信號,則進程收到SIGALRM信號後,缺省的動作就是終止當前進程。
SIGALRM信號成功安裝後,在什麼情況下進程會收到該信號呢?這就要依賴於Linux提供的定時器功能。在Linux系統下,每一個進程都有惟一的一個定時器,該定時器提供了以秒爲單位的定時功能。在定時器設置的超時時間到達後,調用alarm的進程將收到SIGALRM信號。
void main()
{
//安裝SIGALRM信號
if(signal(SIGALRM,CbSigAlrm)==SIG_ERR)
{
perror("signal");
return;
}
//關閉標準輸出的行緩存模式
setbuf(stdout,NULL);
//啓動定時器
alarm(1);
//進程進入無限循環,僅僅能手動終止
while(1)
{
//暫停,等待信號
pause();
}
}
alarm函數的使用:
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
static int flag = 0;
void handle(int signum){
printf("hello world %d\n", flag++);
alarm(1);
}
int main() {
alarm(1);
signal(SIGALRM, handle);
while(1);
}