[comp.lang.c] Question about popen and pclose

tsai@nynex1.UUCP (Nelson Tsai) (08/11/88)

I have some questions about popen function in C.
According to the reference manual, popen should come with pclose.
But, in my Sun OS 3.5 interesting thing happened if I forgot
to put pclose after popen. For instance, the following program works:

#include	<stdio.h>
main() 
{
	int i ;
	for(i=1;i<100;i++) 
		proc(i);
}

proc(i)
int	i;
{
	FILE *gg;
	gg = popen("date","r");
	printf("%d \n",i);
}

But, if the function proc() was changed to :

proc(i)
int	i;
{
	FILE 	*gg;	
	char	ss[200];
	gg = popen("date","r");
	printf("%d \n",i);
	fgets(ss,200,gg);
}

Then, after executed about 20 times, it caused segmentation fault
(core dumped).  Why is that ?  Why reading from the pipe cause the
segmentation fault ?

bill@proxftl.UUCP (T. William Wells) (08/12/88)

In article <364@nynex1.UUCP> tsai@nynex1.UUCP (Nelson Tsai) writes:
: Then, after executed about 20 times, it caused segmentation fault
: (core dumped).  Why is that ?  Why reading from the pipe cause the
: segmentation fault ?

That's an easy one.  You ran out of fd's and the popen call
failed.  It returned a null pointer and fgets tried to
dereference it.  Thus the core dump.  When you didn't include the
fgets, the pointer was never dereferenced, hence no core dump.