execute commands in sequence such that each one uses the output of the previous one in c

73 Views Asked by At

I want to write a c code that receive sequence of commands separated by '|' from standard input (like 'ls -a | grep x', ...) and print the final result of executing it. each command uses the output of the previous command as input and I want to execute each command in a new process and communicate between processes using the dup2() function and pipe. here is a template code how can complete the inside of while loop ?

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

#define MAX_INPUT_LEN 100

void execute (char* token) {
    // this function executes the single command
}

int main() {
    char inp[MAX_INPUT_LEN];
    printf("Enter a command:\n");
    fgets(inp, sizeof(inp), stdin);

    char* token = strtok(inp, "|");

    while (token != NULL) {
        
        // to complete
        
        token = strtok(NULL, "|");
    }

    return 0;
}

I tried using pipe to send output of a process to next process but I didn't know how to use the dup2() function.

0

There are 0 best solutions below