Search code examples
cpipestdin

Terminate C program which stdin is linked to output of other program


I have a program x, which I want to cleanly terminate. You can run it by simply doing ./x and use the terminal to write lines to stdin directly and terminate it by writing exit.

However, if you use: cat file.txt | ./x, the stdin is now piped from the file and therefore you can never type exit.

The best way to end this program would be for it to automatically terminate once the last line was read from the file.

Alternatively, I'd like to re-route stdin back to the terminal if that is at all possible, to further allow manual input as before.

Here is some sample code:

int main() {
  // ...
  while (ongoing) {

    size_t n = 0;
    char* ln = NULL;

    getline(&ln, &n, stdin);

    strtok(ln, "\n");
    strtok(ln, "\r");

    if (strcmp("exit", ln) == 0) {
      break;
    }
    //...
  }
}

Solution

  • When you have read all the input from a pipe, EOF will be raised up to indicate that the full input has been reached. In your example, this will be rougly equivalent with exit, so you can also check the return value of getline to see if the EOF has reached (in which case -1 will be returned).