案例代码
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
void *func(void *arg)
{
char str[50];
FILE* fp = fdopen((int*)arg, "r");
printf("fgets\n");
fgets(str, 20, fp);
exit(-1);
}
void main() {
pthread_t ntid;
int pipefd[2] = {0};
if (pipe(pipefd) == -1)
{
perror("pipe");
}
pthread_create(&ntid, NULL, func, (void*)pipefd[0]);
sleep(1);
printf("fflush\n");
fflush(NULL);
close(pipefd[0]);
close(pipefd[1]);
printf("success\n");
}
现象
fflush(NULL) 卡死.
pstack 显示卡在 __lll_lock_wait_private
调用栈信息:
Thread 2 (Thread 0x7ffff7dcf700 (LWP 8812)):
#0 0x00007ffff7ec1f84 in read () from /lib64/libc.so.6
#1 0x00007ffff7e51c98 in __GI__IO_file_underflow () from /lib64/libc.so.6
#2 0x00007ffff7e52dd6 in _IO_default_uflow () from /lib64/libc.so.6
#3 0x00007ffff7e4622a in _IO_getline_info () from /lib64/libc.so.6
#4 0x00007ffff7e4523f in fgets () from /lib64/libc.so.6
#5 0x000000000040122e in p ()
#6 0x00007ffff7fa14a7 in start_thread () from /lib64/libpthread.so.0
#7 0x00007ffff7ed13e3 in clone () from /lib64/libc.so.6
Thread 1 (Thread 0x7ffff7dd0740 (LWP 8811)):
#0 0x00007ffff7e551cb in __lll_lock_wait_private () from /lib64/libc.so.6
#1 0x00007ffff7e5382c in _IO_flush_all_lockp () from /lib64/libc.so.6
#2 0x00000000004011eb in thr_fn ()
#3 0x00000000004012b6 in main ()
原因分析
先看看 fflush
的官方描述
If the given stream was open for writing (or if it was open for updating and the last i/o operation was an output operation) any unwritten data in its output buffer is written to the file.
If stream is a null pointer, all such streams are flushed.
简单来说就是 fflush
会刷新打开
的fd stream.
如果入参是NULL
, 则刷新所有的fd sream.
再看看fgets
Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.
A newline character makes fgets stop reading, but it is considered a valid character by the function and included in the string copied to str.
简单来说,fgets
会从给定的fd stream 读取数据,并存入buffer.
但这里没有说到的一点是:fgets
is a blocking
read.
它会一直阻塞直到fd stream 有数据。
所以如果当fd steam 没有数据,又没有结束,比如fd是一个还没传数据的pipe
,那么read
这个动作一直会阻塞在这个fd 上。
然后,当fflush
尝试去刷新这个fd时,会因为拿不到锁(锁一直被read
拿着)而一直阻塞。
解决办法
应该尽量避免在代码中以阻塞的方式读fd stream, 除非我们确定当前一定有数据。
可以通过select
, poll
, epoll
等异步I/O 来等到fd stream 有可用数据后,再去读,避免阻塞。
修改后的代码
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>
#include <poll.h>
void *func(void *arg)
{
char str[50];
FILE* fp = fdopen((int*)arg, "r");
struct pollfd readFds = {0};
readFds.fd = (int*)arg;
readFds.events = POLLIN;
printf("poll\n");
if (0 < poll(&readFds, 1, -1))
{
printf("fgets\n");
fgets(str, 20, fp);
}
exit(-1);
}
void main() {
pthread_t ntid;
int pipefd[2] = {0};
if (pipe(pipefd) == -1)
{
perror("pipe");
}
pthread_create(&ntid, NULL, func, (void*)pipefd[0]);
sleep(1);
printf("fflush\n");
fflush(NULL);
close(pipefd[0]);
close(pipefd[1]);
printf("success\n");
}