所以我有一个从父进程到子进程的文件流 - 大多数时候它工作正常.但是,当快速读取多次时,使用fgets()将返回NULL并将错误设置为"资源暂时不可用".问题是间歇性的 - 并且运行执行读取的脚本有时会使fgets返回NULL,有时会返回NULL.
谁能帮我阻止这个错误发生?谢谢!
编辑:这里有一些代码..我不确定其他代码会有什么用处?有很多
// this is the bit that gets a line from the child
if( fgets( line, MAX_LINE_LENGTH, fpin ) == NULL ) {
if( ferror(fpin) ) {
perror("error on stream fpin");
}
free( line );
return FAIL;
}
Run Code Online (Sandbox Code Playgroud)
根据要求,打开管道并处理子进程的代码.
// set up pipes
int readPipe[2]; // child -> parent communication
int writePipe[2]; // parent -> child communication
int errorPipe[2]; // child -> parent, to check for errors in exec
/* create pipe */
pipe( readPipe ); // error if return val < 1 for any
pipe( writePipe );
pipe( errorPipe );
pid_t pid; /* process id when we fork */
pid = fork(); /* create new child */
if( pid == 0 ) { /* pid == 0 indicates child process */
// close unused fds
close( PARENT_READ );
close( PARENT_WRITE );
close( errorPipe[0] );
dup2( CHILD_READ, 0 ); // replace stdin with pipe in
dup2( CHILD_WRITE, 1 ); // replace stdout with pipe out
/* replace child process with program to run */
execvp(args[0], args);
// if we get here, exec failed so inform the parent
char *error_message = "exec failed";
write( errorPipe[1], error_message, strlen(error_message)+1 );
exit(-1);
}
Run Code Online (Sandbox Code Playgroud)
caf*_*caf 10
这意味着有人将标准输入文件描述符设置为非阻塞.
(资源暂时不可用是与EAGAIN/ 对应的错误消息EWOULDBLOCK,read()仅当选择了非阻塞IO并且没有要读取的数据时才会返回该错误消息).
请注意,在执行子进程之前,父进程可能会将文件描述符设置为非阻塞.
进一步调查的一些想法:
如果你strace()是子进程,哪个系统调用正在返回EAGAIN?哪个文件描述符号?
printf("%d\n", fcntl(fileno(fpin), F_GETFL));在失败之前输出的是什么fgets()?