[comp.unix.questions] Odd ouput redirection in background script

flan@cics.Berkeley.EDU (Ian Flanigan) (02/05/91)

Today I was cooking up a small program to save me the trouble of having to
wait for my rsh's to finish:

/* Background Processes */
#include <stdio.h>

main(argc, argv)
int argc;
char *argv[];
{
  if (fork()) 
      exit(0);
  execvp(argv[0],&argv[1]);
  printf("OOps\n");
}

I used the following script to give it a test:

#!/bin/csh

ls > /tmp/tt$$

Then I typed, "background test_scr" to give it a test and it worked fine;
I got the output in the file in /tmp and everything.  I then tried to use
it with rsh and it was a complete failure.  Right away I remebered that
the child process inherits everything, so I needed to close stdin and
stdout.  So the program became:

/* Background Processes */
#include <stdio.h>

main(argc, argv)
int argc;
char *argv[];
{
  if (fork()) 
    exit(0);
  close(0);
  close(1);
  execvp(argv[0],&argv[1]);
  printf("OOps\n");
}

Easy.  Now I gave it a test with, "background test_scr" and it wrote the
directory listing to my screen.  My question: Why?  Not only did I close
stdout, but I also had it re-directed in the script.  Is it a probelem
with the shell?

I've gotten the program to work the way I want it to, now, but I am
baffled by the odd behavior.

Thanks for any info.

-- 
Ian Flanigan

flan@cics.wustl.edu              "You can never have too many napkins."
wucs1.wustl.edu!cics!flan@uucp

pfalstad@phoenix.Princeton.EDU (Paul Falstad) (02/06/91)

flan@cics.Berkeley.EDU (Ian Flanigan) wrote:
>#!/bin/csh
>ls > /tmp/tt$$

>  close(0);
>  close(1);
>  execvp(argv[0],&argv[1]);

>Easy.  Now I gave it a test with, "background test_scr" and it wrote the
>directory listing to my screen.  My question: Why?  Not only did I close
>stdout, but I also had it re-directed in the script.  Is it a probelem
>with the shell?

Yes, this is a bug in csh.  You should not call csh with stdin closed;
you should at least assign it to /dev/null.  If you don't, csh will get
the file descriptors confused, so that stdout will become stdin, and stderr
will become stdout.  The output of ls in your case was being written to
stderr.  This is in the csh bug list, which I ftp'ed from I forget
where.

I know you mentioned that you got it working some other way, but you
might want to check out question #12 in the FAQ for more info on how to
get rsh to work the way you want it to.

--
Paul Falstad, pfalstad@phoenix.princeton.edu PLink:HYPNOS GEnie:P.FALSTAD
10 PRINT "PRINCETON CS"          | #include <std.disclaimer.h>
20 GOTO 10                       | I think sexual ecstasy's overrated.