linux下非同步IO的簡單例子

2021-06-10 07:11:04 字數 1242 閱讀 9655

首先,貼一下非同步io中用的的一些結構體,因為平常很少用,整理起來方便檢視。

aio.h中的struct aiocb

struct aiocb;
siginfo.h中的struct sigevent和union sigval

typedef struct sigevent _sigev_thread;  

} _sigev_un;

} sigevent_t;

/* posix names to access some of the members. */  

# define sigev_notify_function _sigev_un._sigev_thread._function

# define sigev_notify_attributes _sigev_un._sigev_thread._attribute

typedef union sigval sigval_t;

例子1:

#include #include #include #include #include #include #include #include void async_read(int s, siginfo_t * info, void * context)  

int main(void)

int i = 0;

while (1)

return 0;

}

執行結果:注意:要加相應的庫,-lrt
$ ./gcc -o test aio_signal.c -lrt  

$ ./test

0 1

h2

ell3

o read=hello

4 ^c

例子2:

#include #include #include #include #include #include #include void async_read(sigval_t val)  

int main(void)

int i = 0;

while (1)

return 0;

}

結果和例子1相同

同步IO和非同步IO 簡單理解

在linux系統中,所有的裝置讀寫都可以看做是檔案的讀寫來進行操作,而對檔案的讀寫一般要經過核心態和使用者態的切換,因此io產生了同步和非同步。同步是阻塞模式,非同步是非阻塞模式。同步就是指乙個程序在執行某個請求的時內候,若該請求需容要一段時間才能返回資訊,那麼這個程序將會一直等待下去,直到收到返回...

linux下Makefile的簡單例子及解釋

對於大一點的專案,makefile都是不可或缺的,這裡記錄乙個自己弄的簡單的例子。有3個file main.cpp main2.cpp main2.h main.cpp main函式所在,呼叫main2.cpp中的乙個外部函式test main2.cpp test函式所在 main2.h test的...

linux下Makefile的簡單例子及解釋

對於大一點的專案,makefile都是不可或缺的,這裡記錄乙個自己弄的簡單的例子。有3個file main.cpp main2.cpp main2.h main.cpp main函式所在,呼叫main2.cpp中的乙個外部函式test main2.cpp test函式所在 main2.h test的...