Note that there are some explanatory texts on larger screens.

plurals
  1. PORun N concurrent processes in C
    primarykey
    data
    text
    <p>I am trying to run N concurrent processes in a C program. I've built a simple example that takes commands as arguments, creates a fork for each one, and executes it.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; int main(int argc, char **argv) { int i; for(i = 1; i &lt; argc; i++) { pid_t pid = fork(); if(pid &lt; 0) { fprintf(stderr, "forking error\n"); exit(1); } else if(pid &gt; 0) { int status; waitpid(pid, &amp;status, 0); printf("Command %s has completed successfully by PID=%d\n", argv[i], pid); } else { char cmd[1024]; sprintf(cmd, "%s", argv[i], i); system(cmd); _exit(1); } } printf("Finished\n"); return 0; } </code></pre> <p>This seems to run the processes correctly, but not concurrently. Any ideas as to what am I doing wrong?</p> <p><strong>EDIT</strong>: I've edited based on suggestions, but this also does not seem to work.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; int main(int argc, char **argv) { int i; pid_t *pids = malloc( sizeof(pid_t) * (argc) ); int *statuses = malloc( sizeof(int) * (argc) ); for(i = 1; i &lt; argc; i++) { pid_t pid = fork(); if(pid &lt; 0) { fprintf(stderr, "forking error\n"); exit(1); } else if(pid &gt; 0) { //int status; //waitpid(pid, &amp;status, 0); //printf("Command %s has completed successfully by PID=%d\n", argv[i], pid); pids[i] = pid; } else { char cmd[1024]; sprintf(cmd, "%s &gt; out.%d", argv[i], i); system(cmd); _exit(1); } } int needtowait = 0; do { needtowait = 0; for(i = 1; i &lt; argc; i++) { if(pids[i] &gt; 0) { if(waitpid(pids[i], &amp;statuses[i], 0) != 0) { pids[i] = 0; char *successstr = "successfully"; if(statuses[i]) { successstr = "unsuccessfully"; } printf("Command %s has completed %s by PID=%d\n", argv[i], successstr, pids[i]); } } else { needtowait = 1; } sleep(0); } } while(needtowait); printf("Finished!\n"); return 0; } </code></pre>
    singulars
    1. This table or related slice is empty.
    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. This table or related slice is empty.
    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