非搁置模式O_NONBLOCK的作用是什么,该如何处理
非搁置模式O_NONBLOCK的作用是什么
小弟在学习linux编程,知道open()里面有个非搁置模式O_NONBLOCK的参数模式,但是不知道它的作用是什么,能不能举个具体点的例子告诉我???????
------解决方案--------------------
以前写的,程序开始后自动计时,十秒后退出。如果输入stop,则立即退出。
小弟在学习linux编程,知道open()里面有个非搁置模式O_NONBLOCK的参数模式,但是不知道它的作用是什么,能不能举个具体点的例子告诉我???????
------解决方案--------------------
以前写的,程序开始后自动计时,十秒后退出。如果输入stop,则立即退出。
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <errno.h>
#include <fcntl.h>
static int thread_exit = 0; /* running state of a thread */
void *showtime(void *arg)
{ /* this is a long-time test */
int *i = arg;
time_t p;
thread_exit = 0;
while (--(*i) > 0) {
printf("---%d---\n", *i);
time(&p);
printf("%s", ctime(&p));
sleep(1);
}
thread_exit = 1;
return ((void *)0);
}
int main(int argc, char **argv)
{
pthread_t tid;
pthread_attr_t attr;
void *tret;
char cmd[16] = { 0 };
int err, times = 10; /* default: test costs 10 secs */
int flag;
/* Use pthread */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
err = pthread_create(&tid, NULL, showtime, ×); /* showtime is a long-time test */
if (err != 0) {
perror("Can't create thread.\n");
exit(1);
}
/* pthread_join(tid,&tret); *//* wait thread to terminate, pthread_join will block the main thread, so we give it up */
flag = fcntl(0, F_GETFL, 0);
flag
------解决方案--------------------
= O_NONBLOCK;
if (fcntl(0, F_SETFL, flag) < 0) { /* fgets no-block now */
perror("Set stdin to non-block fails.");
exit(1);
}
for (;;) {
if (thread_exit)
break;
if (fgets(cmd, sizeof(cmd) - 1, stdin) != NULL) {
if (strncmp(cmd, "stop", 4) == 0) {
pthread_cancel(tid); /* cancel thread */
pthread_attr_destroy(&attr);
flag &= ~O_NONBLOCK;