0

I'm writing a code in C and I'm trying to use 3 commands (echo, grep and wc) with excev() but its not working. It is possible to do it and if not any other solution or I will need to use fscanf().

How I want it to print in bash: code in bash

The code I wrote in C, which is not working:

    void count_lines(short unsigned int G)
    {
    g = 0;
    while (g <= G) {
        char *const command[] = {"echo","Number of lines by processes of generation",g,"is","`grep","-o","G is",g,"out.txt","|","wc","-l",NULL };
        execv("/bin/echo /usr/grep bin/wc", command);
        g++
    }
}
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
ocram ali
  • 1
  • 1
  • 1
    Please don't post code as image, copy and paste the code within the post itself. – kiner_shah Nov 10 '21 at 09:11
  • In `excev` , you need to pass file you want to run, and list of arguments with argument[0] being command itself. `excev("/bin/echo",argv[])` . `argv[0] = "echo" `, `argv[1] = string.` – Tauqeer Akhtar Nov 10 '21 at 09:12
  • but how I use pipe in execv()? like i did in the terminal, need that echo grep and wc will work togther – ocram ali Nov 10 '21 at 09:26
  • Please see [this related post](https://stackoverflow.com/questions/47767995/exec-and-pipe-between-child-process-in-c) with particular reference to [this link](https://stackoverflow.com/questions/13801175/classic-c-using-pipes-in-execvp-function-stdin-and-stdout-redirection). – G.M. Nov 10 '21 at 09:42
  • 2
    You need to start a shell and have the shell executing the commands. like: `args=['bash', '-c', 'command1 "arg1"; command2 "arg2; ...']` – hek2mgl Nov 10 '21 at 11:04
  • 1
    `execv` never returns (unless it fails). If you want to `exec` multiple processes, you need to `fork/exec`. – William Pursell Nov 10 '21 at 22:45
  • A pipe instructs the shell to run `mkfifo()` to create a pipeline, `fork()` off a separate process for each side of the pipe, and then call `execve()` for each program. It's not just one `execv()` -- it's one _per pipeline element_. – Charles Duffy Nov 10 '21 at 22:48
  • Also, this is purely a C question. Do not use the bash tag unless you're asking about bash itself -- not shells in general, not the POSIX sh specification, not a simplified teaching shell, specifically _bash_. (Similarly, the terminal tag should only be used for questions about terminals -- not programs that run with their output to a terminal, but actual terminals as such). – Charles Duffy Nov 10 '21 at 22:49

0 Answers0