Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm including the source of a small library I've written a while ago. That should get you started. Fork / pipe / exec isn't really that easy (especially with all the variants of <code>exec</code>) and it took me a while too. So here goes:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; #include &lt;sys/stat.h&gt; #include "limbo.h" int out_pipe[2], err_pipe[2]; int run_command(char *argv[], int *out_length, int *err_length){ pid_t pid; int status = 0; struct stat out_stat, err_stat; pipe(out_pipe); //create a pipe pipe(err_pipe); if(!(pid = fork())) //spawn child { // Child. Close the read end of the pipe close(out_pipe[0]); close(err_pipe[0]); // redirect stdout and stderr to the write end of the pipe dup2(out_pipe[1], STDOUT_FILENO); dup2(err_pipe[1], STDERR_FILENO); status = execv(argv[0], argv); //child will terminate here } //Only parent gets here. Close write end of the pipe close(out_pipe[1]); close(err_pipe[1]); //or wait for the child process to terminate waitpid(pid, &amp;status, 0); fstat(out_pipe[0], &amp;out_stat); fstat(err_pipe[0], &amp;err_stat); *out_length = (int) out_stat.st_size; *err_length = (int) err_stat.st_size; return status; } int read_buffers(char *out_buffer, int out_length, char *err_buffer, int err_length){ out_buffer[read(out_pipe[0], out_buffer, out_length)] = 0; err_buffer[read(err_pipe[0], err_buffer, err_length)] = 0; return 0; } </code></pre> <p>The comments in the code should help you to understand the code. Feel free to reuse.</p> <h3>Edit</h3> <p>In response to your comment:</p> <p>The <code>waitpid()</code> call makes the parent process wait for the termination of the child process. If you want both processes to run in parallel, you need to get rid of <code>waitpid()</code> in the place that I use it. <em>But be careful:</em> without a call to one of the <code>wait</code> functions your child process will become a zombie once it finishes. It is your responsibility to keep an eye on your child process and to <code>wait</code> for it so the process can be cleaned up by the kernel.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload