One file input to two program in script

95 views Asked by At

Hi I have a script that run two program

#Script file 
./prog1
./prog2

prog1 is a C program

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv){
  printf("prog1 running\n");
    int tmp;
    scanf("%d", &tmp);
    printf("%d\n", tmp+10);
    printf("prog1 ended\n");
    return 0;
}

prog 2 is a C program as well

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv){
    printf("prog2 running\n");
    int tmp;
    scanf("%d\n", &tmp);
    printf("%d\n", tmp+10);
    printf("prog2 ended\n");
    return 0;
}

I run the command

./script < file

where file is

123
456

The output is

prog1 running
133
prog1 ended
prog2 running
10
prog2 ended

It seems like prog2 did not get the input from file, what is happening under the hood?

Will it be possible that prog2 took "\n" instead of a number?

2

There are 2 answers

0
Toby Speight On

scanf reads buffered input. So when your first program reads from stdin, it speculatively reads ahead all the available input to make future reads from stdin faster (through avoiding having to make so many system calls). When the second program runs, there's no input left, and (since you failed to check the result of scanf()) you end up with 0 in tmp.

You should be able to modify the buffering strategy in your application (at the expense of speed) using the setvbuf() standard function.

0
Alepac On

Your script should be this:

#!/bin/bash
exec 3<&1
tee  >(./prog2 >&3) | ./prog1

This use the tee command to duplicate stdin and the recent >() bash feature to open a temporary filedescriptor. (the use of filedesriptor 3 is done to split the stdout without parallelism).

See this answer to read the whole story.