写一个linux下使用O_NONBLOCK的write例子
时间: 2023-06-07 14:09:46 浏览: 90
好的,以下是一个使用O_NONBLOCK的write例子:
```
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main() {
int fd = open("testfile.txt", O_WRONLY | O_CREAT, 0644);
if (fd == -1) {
perror("open failed");
exit(EXIT_FAILURE);
}
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) {
perror("fcntl F_GETFL failed");
exit(EXIT_FAILURE);
}
if (fcntl(fd, F_SETFL, flags | O_NONBLOCK) == -1) {
perror("fcntl F_SETFL O_NONBLOCK failed");
exit(EXIT_FAILURE);
}
char *data = "This is a test string.\n";
int total = strlen(data);
int written = 0;
while (written < total) {
int result = write(fd, data + written, total - written);
if (result == -1) {
if (errno == EAGAIN) {
// Resource temporarily unavailable
continue;
} else {
// Other error
perror("write failed");
exit(EXIT_FAILURE);
}
} else {
written += result;
}
}
if (close(fd) == -1) {
perror("close failed");
exit(EXIT_FAILURE);
}
printf("Data written successfully.\n");
exit(EXIT_SUCCESS);
}
```
这个程序会创建一个名为testfile.txt的文件,并将字符串"This is a test string.\n"写入到文件中。其中通过fcntl函数设置文件描述符为非阻塞模式,如果write函数返回EAGAIN错误表示资源暂时不可用,则继续循环写数据。最后通过close函数关闭文件。
阅读全文