1

when I put a no output program on the left of pipe, such as:

// program a
int main() {
    char s[255];
    scanf("%s", s);
    return 0;
}

and a program with input & output on the right:

// program b
int main() {
    char s[255];
    scanf("%s", s);
    for(char *c = s; *(c) != '\0'; c++) printf("%d ", *c);
    return 0;
}

when I try to connect them with pipe:

$ ./a | ./b

No matter what the input is, I always get two ascii codes: 64 & 3 in my computer, Even though I know that 'a' has no output.

I want to know if this is because of my program, or because of the shell, or because of the pipeline, or something else...

yztz
  • 11
  • 1
  • 1
    Did you try to initialize `s` to all zero before doing the `scanf` (probably easiest to do by writing `static char s[255];`? – user1934428 Dec 02 '21 at 10:27
  • @user1934428 Thank you!!! It works! Very simple but undetectable error : ( – yztz Dec 02 '21 at 11:54
  • And if you ever try something like this in a real application, please never, ever use `scanf` in this way, or you will be grilled during the next code review.... – user1934428 Dec 02 '21 at 11:57

1 Answers1

0

The pipe means "run program a, and use its output as input for program b". Both programs get executed.

Interesting is e.g. where cat comes in that just takes input and outputs it:

$ ls
file  README-cloudshell.txt  terraform.tfstate  test.php
$ ls | cat
file
README-cloudshell.txt
terraform.tfstate
test.php

And this also explains why "hello" is not printed here:

$ echo hallo | ls
file  README-cloudshell.txt  terraform.tfstate  test.php
Thorsten Staerk
  • 1,114
  • 9
  • 21
  • I already know roughly where my problem is: `scanf` returns `EOF`, whcih means `fd[1]` has been closed because of termination of the previous program. But I still wonder why it gives two fixed ascii codes: `64` & `3`, which means '@' and 'end of text'. Is this some mechanism of pipe? – yztz Dec 02 '21 at 06:38
  • OK, are you expecting a solution to a problem or an explanation? – Thorsten Staerk Dec 02 '21 at 08:42