用fork创建进程

时间:2017-05-15 08:43:08

标签: c unix process fork

我试图了解如何创建fork树,有没有简单的方法来理解它?

例如:

$paper_id_variable

2 个答案:

答案 0 :(得分:0)

来自linux手册:

  

fork()通过复制调用进程来创建一个新进程。

基本上它创建了一个新的进程,称为子进程,它是一个完全重复的,具有相同代码的调用进程,被称为父进程,除了少数事情(看看{{1} })。如果您是父母,则会返回let httpCookie = HTTPCookie.init(properties: [HTTPCookiePropertyKey.version : "0", HTTPCookiePropertyKey.name : "MYTestID", HTTPCookiePropertyKey.value : "983724dd3dea4924b8d675b0df08b611", HTTPCookiePropertyKey.expires : "2027-05-13 09:21:23 +0000"]) if let cookie = httpCookie { HTTPCookieStorage.shared.setCookie(cookie) } ,如果您是孩子,则会返回man fork或{0}} 。这是叉树的代码示例:

child process ID

答案 1 :(得分:0)

每次打电话给fork()时,你都会创建一个孩子,它具有父亲到目前为止的确切代码,但是它的拥有内存映射。

然后你必须使用相同的代码进行2个进程。如果你想让他们做些不同的事情,你必须使用fork()的回复。 Fork返回孩子的 pid ,然后分配'''''''它在父亲的记忆中。通过该机制,父亲可以使用其仅为他所知的pid(进程ID)来引用该子进程。如果孩子试图通过fork()查看为其创建的确切pid,那么它就不会为零(因为fork将PID返回到其他进程的进程)。

上面的示例代码如下:

void  main(void)
{
    char sth[20]="something";
    pid_t  pid;

    pid = fork(); // Create a child
    // At this line (so this specific comment if you may like) has 2 processes with the above code
    printf("I am process with ID<%ld> and i will print sth var <%s>", getpid(),sth);
    // The above printf would be printed by both processes because you haven't issued yet a way to make each process run a different code.
    // To do that you have to create the following if statement and check PID according to what said above.
    if (pid == 0) // If PID == 0, child will run the code
        printf("Hello from child process with pid <%ld>",getpid());
        printf(", created by process with id <%ld>\n",getppid());
    else          // Else the father would run the code
        printf("Hello from father process with pid <%ld>",getpid());
}

我试着像我一样天真。希望它有所帮助。

相关问题