Portál AbcLinuxu, 6. prosince 2025 12:32
Můj problém je v ukázce kódu níže – jakmile nastavím stdin flag O_NONBLOCK, následující výstup na stdout se po chvíli zastaví a nehodlá pokračovat. Jakmile flag na stdin zruším, vše opět funguje jak má. Je to standardní chování? Dá se ovlivnit?
Díky za každou reakci
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char** argv)
{
int flags, i;
char foo[]=
"% 6d 012345678901234567890123456789012345678901234567890123456789\n";
// vypise se vse
for (i= 0; i < 10000; i++) printf(foo, i);
// vypise se
puts("\nklavesu...");
fgetc(stdin);
flags= fcntl(fileno(stdin), F_GETFL, 0);
fcntl(fileno(stdin), F_SETFL, flags | O_NONBLOCK);
// NEvypise se vse
for (i= 0; i < 10000; i++) printf(foo, i);
// NEvypise se ani tohle
puts("\n*** KONEC ***");
fcntl(fileno(stdin), F_SETFL, flags);
// tohle se uz vypise
puts("\nklavesu...");
fgetc(stdin);
// vypise se vse
for (i= 0; i < 10000; i++) printf(foo, i);
// vypise se
puts("\n*** KONEC ***");
return (0);
}
using standard I/O with nonblocking descriptors, a recipe for disaster(ale celé som to nečítal, takže neviem, v čom je ten problém) Tento program dokazuje, že zmena stdin na neblokujúci, zmení aj stdout a stderr (aspoň u mňa).
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
int main(int argc, char** argv)
{
int flags;
fprintf(stdout, "stdin: %s\n", (fcntl(fileno(stdin), F_GETFL, 0) & O_NONBLOCK) ? "NONBLOCK" : "BLOCK");
fprintf(stdout, "stdout: %s\n", (fcntl(fileno(stdout), F_GETFL, 0) & O_NONBLOCK) ? "NONBLOCK" : "BLOCK");
fprintf(stdout, "stderr: %s\n", (fcntl(fileno(stderr), F_GETFL, 0) & O_NONBLOCK) ? "NONBLOCK" : "BLOCK");
flags= fcntl(fileno(stdin), F_GETFL, 0);
fcntl(fileno(stdin), F_SETFL, flags | O_NONBLOCK);
fprintf(stdout, "stdin: %s\n", (fcntl(fileno(stdin), F_GETFL, 0) & O_NONBLOCK) ? "NONBLOCK" : "BLOCK");
fprintf(stdout, "stdout: %s\n", (fcntl(fileno(stdout), F_GETFL, 0) & O_NONBLOCK) ? "NONBLOCK" : "BLOCK");
fprintf(stdout, "stderr: %s\n", (fcntl(fileno(stderr), F_GETFL, 0) & O_NONBLOCK) ? "NONBLOCK" : "BLOCK");
fcntl(fileno(stdin), F_SETFL, flags);
return (0);
}
Tiskni
Sdílej:
ISSN 1214-1267, (c) 1999-2007 Stickfish s.r.o.