如何fork()的工作? [英] How does fork() work?

查看:288
本文介绍了如何fork()的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

林真正的新分叉,什么是PID在这个code在做什么?有人可以请解释在行X和Y线什么出来?

 的#include< SYS / types.h中>
#包括LT&;&stdio.h中GT;
#包括LT&;&unistd.h中GT;
#定义5号
INT NUMS [SIZE] = {0,1,2,3,4};
诠释的main()
{
    INT I;
    将为pid_t PID;
    PID =叉();
    如果(PID == 0){
        对于(i = 0; I<大小;我++){
            NUMS [I] * = -i;
            的printf(子数:%d,NUMS [I]); / *行x * /
        }
    }
    否则如果(PID大于0){
        等待(NULL);
        对于(i = 0; I<大小;我++)
            的printf(父数:%d,NUMS [I]); / * LINE Y * /
    }
    返回0;
}


解决方案

叉()复制的过程中,因此调用fork之后其实有2你的程序运行的情况下,

你怎么知道哪个进程是原始(父)之一,这是新的(孩子)呢?

在父进程,子进程的PID(这将是一个正整数)从返回叉()。这就是为什么如果(PID大于0){/ *母公司* /} code ++工程。在子过程中,叉()只返回 0

这样,因为如果(PID大于0)检查,父进程和子进程会产生不同的输出,你可以看到的here (由@jxh在评论中提供)。

Im really new to forking, what is the pid doing in this code? Can someone please explain what comes out at line X and line Y ?

#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
#define SIZE 5
int nums[SIZE] = {0,1,2,3,4};
int main()
{
    int i;
    pid_t pid;
    pid = fork();
    if (pid == 0) {
        for (i = 0; i < SIZE; i++) {
            nums[i] *= -i;
            printf("CHILD: %d ",nums[i]); /* LINE X */
        }
    }
    else if (pid > 0) {
        wait(NULL);
        for (i = 0; i < SIZE; i++)
            printf("PARENT: %d ",nums[i]); /* LINE Y */
    }
    return 0;
}

解决方案

fork() duplicates the process, so after calling fork there are actually 2 instances of your program running.

How do you know which process is the original (parent) one, and which is the new (child) one?

In the parent process, the PID of the child process (which will be a positive integer) is returned from fork(). That's why the if (pid > 0) { /* PARENT */ } code works. In the child process, fork() just returns 0.

Thus, because of the if (pid > 0) check, the parent process and the child process will produce different output, which you can see here (as provided by @jxh in the comments).

这篇关于如何fork()的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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