tags:

views:

45

answers:

2

Hello,

I have been stuck on this for some time. Let's say I have a C program like the following. I want to be able to send this program some string and get the control after that. If I do:


--> cat myfile | myprogram
or
--> echo "0123" | myprogram
or
--> myprogram < myfile
I get the ouput (myfile contains "0123")
30 31 32 33

Using the -n option raises a segfault
--> echo -n mystring | ./test
zsh: done echo -n "0123" |
zsh: segmentation fault ./test

I also tried with a named pipe, but it didn't work either.

I would like to be able to do something like cat myfile | myprogram and get back the control so that I can type other characters.

  1 #include  <stdlib.h>
  2 #include  <stdio.h>
  3 
  4 int main (int argc, char *argv[]) {
  6   int i = 0, j;
  7   unsigned char buf[512];
  8   unsigned char x;
  9 
 10   while ((x = getchar()) != '\n') {
 11     buf[i] = x;
 12     i++;
 13   }
 14 
 16   for (j = 0; j < i; j++) {
 17     printf("%x ", buf[j]);
 18   }
 19   printf ( "\n" );
 20 
 21   return EXIT_SUCCESS;
 22 }  // end of function main
A: 

In this example I use tail -f, not your C program

 mkfifo /tmp/pipe   # Open Pipe
 tail -f /tmp/pipe &    #  Start your program and put it into the background

Now you also can send data to your program that runs in the background

 echo "foobar" > /tmp/pipe

I hope this helps?

Alex
edit: Thanks for your answer!This works well with tail and -f (follow) option, but does not if you remove it.So it does not work for myprogram either.I suspect tail -f won't stop after receiving the EOF or end of string character or something similar; but myprogram will.
Ramses
Actually, I don't think your program will terminate on end of string (except by segfaulting) since getchar only tests against EOF (and is not even guaranteed to succeed at that) and the program only tests against newline.
Nathon
A: 

You could modify your program to accept 1 null character then continue on...it might work:

replace line 10 with something like

while (TRUE)
{
    x = getchar();
    if (x == '\n')
        break;
    if (x == '\0')
    {
        if (seen)
            break;
        seen = TRUE;
    }
...
Nathon
Well the idea is that I actually don't write the program myself...
Ramses
If you can't edit the program you're using, then you're SOL. I recommend you use tail.
Nathon