unistd.h


unistd.h是unix std的意思,是POSIX標准定義的unix類系統定義符號常量的頭文件,

包含了許多UNIX系統服務的函數原型

unistd.h在unix中類似於window中的windows.h!

#ifdef WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif

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);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM