为什么我在这里分叉5次以上? [英] Why am I forking more than 5 times here?

查看:56
本文介绍了为什么我在这里分叉5次以上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我在这里有代码,我希望它严格执行ls -l 5次,但它似乎运行的次数更多.我在这里做错了什么?我想运行ls 5次,所以我分叉5次.也许我不正确地理解等待的概念?我看了很多教程,似乎没有一个可以使用fork彻底解决多个过程.

So I have code here, and I expected it to strictly run ls -l 5 times, but it seems to run far more times. What am I doing wrong here? I want to run ls 5 times, so I fork 5 times. Perhaps I don't understand the concept of wait properly? I went over a ton of tutorials, and none seem to tackle multiple processes using fork thoroughly.

#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;
    }





}

推荐答案

在C中使用fork时,您必须想象将流程代码和状态复制到新流程中,然后从该处开始执行关闭.

When you use fork in C, you have to imagine the process code and state being copied into a new process, at which point it begins execution from where it left off.

在C语言中使用exec时,您必须想象如果调用成功,整个过程将被替换.

When you use exec in C, you have to imagine that the entire process is replaced if the call is successful.

这是您的代码,已重新编写以产生预期的行为.请阅读评论.

Here is your code, re-written to produce the expected behavior. Please read the comments.

#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;
}

这篇关于为什么我在这里分叉5次以上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆