fcntl() 函数可以设置文件描述符的阻塞特性。
1.fcntl设置阻塞特性
实例:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd_pipe[2];
pid_t pid;
if (pipe(fd_pipe) < 0)
{ // 创建无名管道
perror("erro to pipe:");
}
pid = fork(); // 创建进程
if (pid < 0)
{ // 出错
perror("error to fork:");
exit(-1);
}
if (pid == 0)
{ // 子进程
sleep(5);
char buf[] = "hello, world!";
write(fd_pipe[1], buf, strlen(buf)); // 写数据
_exit(0);
}
else if (pid > 0)
{ // 父进程
fcntl(fd_pipe[0], F_SETFL, O_NONBLOCK); // 非阻塞
while (1)
{
char str[50] = {0};
read(fd_pipe[0], str, sizeof(str)); //读数据
printf("str=%s\n", str);
sleep(1);
}
}
return 0;
}
运行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
str=
str=
str=
str=
str=
str=hello, world!
str=
str=