bash, named pipe and lock :(

Sauron The Dark <[email protected]> Sun, 29 Aug 2004 23:59:34 +0200
Newsgroups gmane.comp.lib.ptyget
Organization NOSC
Message-ID <[email protected]>
  Hi,

I wanted to write a script, not using expect, to be able to change a 
password in a non-interactive way, knowing that my version of passwd 
doesn't support the "--stdin" option.

I downloaded "ptyget" from http://multivac.cwru.edu/ptyget/ and the pts 
patch to have it working under my debian.

Then, I wrote this script and called it setpass.sh :

#!/bin/bash
wf="./waitfor"
pid=$$

mknod out.${pid} p

( ${wf} 'password:' <out.${pid} ; echo "$2" ; ${wf} 'password:' <out.${pid} ; echo "$2" ; cat >/dev/null <out.${pid} ) | ( ptyget passwd "$1" &>out.$$ )

rm -f out.${pid}

So, calling "./setpass.sh username password" from a script should allow 
me to change/set many passwords at a time.

The code for "waitfor" is the following :

#include <stdio.h>
#include <string.h>

#define ERROR 1

int readUntilString(FILE *f,char *s)
{
	int p=0;
	int l=strlen(s);
	int b;

	while (!(p==l))
	{
		if ((b=fgetc(f))==EOF)
		{
			return ERROR;
		}

		if (b!=s[p])
			p=0;
		else
			p++;
	}
	return 0;
}

int main(int argc, char *argv[])
{
	if (argc<2)
		return 0;
	if (!*argv[1])
		return 0;
	
	return readUntilString(stdin,argv[1]);
}

Now, if I make another script to test the whole thing, it could look 
like this :

#!/bin/bash
while /bin/true ; do
{
	date # just to see something changing on the screen
	./setpass.sh username password
}
done

My problem is setpass.sh locks.
I've tried to modify waitfor.c so that it doesn't stop and goes on 
reading after EOF (in case of an empty pipe) but it doesn't help.

My guess, is that waitfor is sometimes launched before passwd (before 
passwd prompt gets written to the named pipe), tries to read from the 
empty pipe and locks...

Any idea on how to solve this ?

Please note that the question isn't about changing passwords, but about 
the use of named pipes in shell scripts without locking. The passwd 
stuff is here to give you a concrete example as a base to describe my 
problem.

Thx in advance...
    FB

<http://flamebalrog.reallyrules.com>