read(stdin, buf, size);
printf(“hello”);
如果read是阻塞的则会停止到read语句不会执行下一个语句;否则不会停止,会执行下一个语句。
#include <stdio.h>
#include <stdlib.h>
#define COUNT 10
int
main()
{
char buf[COUNT];
size_t nbytes;
int n;
for (n = 0; n< COUNT; n++)
buf[n] = 0;
nbytes = 10;
read(stdin, buf, nbytes);
printf("hello\n");
printf("%s\n", buf);
}
这个标准输入,我想应该是会阻塞的,结果是没有阻塞:
没有停止等待输入就直接输出了。这是有问题的,stdin是指针类型而read要求用int型的参数。
最后,改成:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define COUNT 10
int
main()
{
char buf[COUNT];
size_t nbytes;
int n, flags;
for (n = 0; n< COUNT; n++)
buf[n] = 0;
if ( (flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0)
{
printf("F_GETFL error");
exit(0);
}
printf("flags:%d\n", flags);
nbytes = 10;
read(STDIN_FILENO, buf, nbytes);
printf("hello\n");
printf("%s\n", buf);
}
结果:
设置nonblock选项后:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define COUNT 10
int
main()
{
char buf[COUNT];
size_t nbytes;
int n, flags;
int fd;
fd = 0;
for (n = 0; n< COUNT; n++)
buf[n] = 0;
if ( (flags = fcntl(STDIN_FILENO, F_GETFL, 0)) < 0)
{
printf("F_GETFL error");
exit(0);
}
printf("flags old:%d\n", flags);
flags |= O_NONBLOCK;
if (fcntl(STDIN_FILENO, F_SETFL, flags) < 0)
{
printf("F_SETFL error");
exit(0);
}
printf("flags new:%d\n", flags);
nbytes = 10;
read(STDIN_FILENO, buf, nbytes);
printf("hello\n");
printf("%s\n", buf);
}
结果:
结果就像我想的那样。read阻塞的话会停止不进行,而非阻塞的话将不等待从stdin读取数据这个动作。