Why am I deploying here more than 5 times?

So, I have the code here, and I expected it to strictly execute ls -l 5 times, but it seems to work a lot more. What am I doing wrong here? I want to run ls 5 times, so I fork 5 times. Perhaps I do not understand the concept of expectation? I looked through a ton of tutorials and no one seems to handle a few processes using fork.

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
    pid_t pidChilds[5];

    int i =0;

    for(i = 0; i<5; i++)
    {
        pid_t cpid = fork();
        if(cpid<0)
            printf("\n FORKED FAILED");
        if(cpid==0)
            printf("FORK SUCCESSFUL");
        pidChilds[i]=cpid;
    }





}
+5
source share
3 answers

When you use fork in C, you must imagine that the process code and state are copied to the new process, after which it starts execution from where it left off.

When you use exec in C, you must imagine that the whole process is replaced if the call succeeds.

, . , .

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
    pid_t cpid;
    pid_t pidChildren[5];

    int i;
    for (i = 0; i < 5; i++)
    {
        cpid = fork();
        if (cpid < 0) {
            printf("fork failed\n");
        } else if (cpid == 0) {
            /*  If we arrive here, we are now in a copy of the
                state and code of the parent process. */
            printf("fork successful\n");
            break;
        } else {
            /*  We are still in the parent process. */
            pidChildren[i] = cpid;
        }
    }

    if (cpid == 0) {
        /*  We are in one of the children;
            we don't know which one. */
        char *cmd[] = {"ls", "-l", NULL};
        /*  If execvp is successful, this process will be
            replaced by ls. */
        if (execvp(cmd[0], cmd) < 0) {
            printf("execvp failed\n");
            return -1;
        }
    }

    /* We expect that only the parent arrives here. */
    int exitStatus = 0;
    for (i = 0; i < 5; i++) {
        waitpid(pidChildren[i], &exitStatus, 0);
        printf("Child %d exited with status %d\n", i, exitStatus);
    }

    return 0;
}
+2

- , .

: , , , - 4 , .

4 , , , 3 .

.

fork() , , , . break; , .

" PID , 0. -1, , errno ."

, if(cpid==0) break;.

+3

Each i'th forkloop starts inside the loop, so it will run the remaining n-iiterations of this loop, recursive playback.

0
source

All Articles