[comp.unix.internals] gets

stanonik@nprdc.navy.mil (Ron Stanonik) (12/11/90)

I just ran into a problem while porting a program from 4.3bsd to
sunos4.1.  The problem is that gets() in signal handlers seems to
reset stdio's write pointer, but not the read pointer.  Here's
an example program.  It use SIGINT to confirm that the user wants
to exit.  If the user answers "n", it returns to the main program,
but that answer fouls up the gets() in the main program.  Is this
a bug or a feature?  Putting a rewind(stdin) at the end of the
handler seems to fix it, but that seems like voodoo programming.

Thanks,

Ron Stanonik
stanonik@nprdc.navy.mil

#include <stdio.h>
#include <signal.h>

void onint();

main()
{
	char buf[1024];

	signal(SIGINT, onint);

	puts("first");
	gets(buf); puts(buf);
	puts("second");
	gets(buf); puts(buf);
	puts("third");
	gets(buf); puts(buf);
}

void
onint()
{
	char buf[1024];

	puts("exit?");
	gets(buf);
	if (!strcmp(buf, "y"))
		exit(0);
	/*rewind(stdin);*/
}


Here's a sample run
arctic[1] ./sig
first
hello
hello
second
^Cexit?
n
arf
f
third
o
arctic[2] exit

rang@cs.wisc.edu (Anton Rang) (12/11/90)

In article <25232@adm.brl.mil> stanonik@nprdc.navy.mil (Ron Stanonik) writes:
>I just ran into a problem while porting a program from 4.3bsd to
>sunos4.1.  The problem is that gets() in signal handlers seems to
>reset stdio's write pointer, but not the read pointer.

  As far as I know, UNIX stdio packages are not re-entrant.  Don't try
to use any of the input routines, in particular, inside a signal
handler.  I'm not sure if the output routines are safe, but I wouldn't
count on them--I've seen implementations of printf() which used a
static buffer internally.

  I've moved followups to comp.unix.programmer, which is probably
where this really belongs... (?)

	Anton
   
+---------------------------+------------------+-------------+
| Anton Rang (grad student) | rang@cs.wisc.edu | UW--Madison |
+---------------------------+------------------+-------------+