【问题标题】:Creation of process with fork用fork创建进程
【发布时间】:2017-05-15 08:43:07
【问题描述】:

我正在尝试了解如何创建分叉树,有什么简单的方法可以理解吗?

示例:

    include<stdio.h>
include<unistd.h>
void main(){

fork();
if fork();
if fork();
fork();
sleep(10);

}

【问题讨论】:

  • 这个不太清楚——具体是什么你不明白?
  • 给你,伙计...GeeksForGeeks
  • @GauravPathak 我真的很新,你有基本的例子吗?
  • 请回答这个question
  • 不确定是什么语言,但不是 C。

标签: c unix process fork


【解决方案1】:

每次您调用fork() 时,您都在创建一个Child,该Child 具有直到此刻父亲所拥有的确切代码,但它具有自己的 内存映射。 p>

然后您必须使用相同代码的 2 个进程。如果你想让他们做一些不同的事情,你必须使用fork()'s return。 Fork 返回孩子的 pid 并在父亲的记忆中“分配”它。通过这种机制,父亲可以使用只有他知道的 pid(进程 ID)来引用孩子。如果孩子试图通过fork() 看到为其创建的确切 pid,它根本不能并且将为零(因为 fork 将 PID 返回给其他 child 进程的进程)。

上面的示例代码如下:

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());
}

我尽可能地天真。希望能有所帮助。

【讨论】:

  • 在 Unix 上,void main(void) 是无条件错误的。 Unix 上的return type for main()int。 (在 Windows 上有一个 get-out 子句,但问题被标记为 Unix,因此 get-out 子句不适用。)
【解决方案2】:

来自 linux 手册:

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

基本上,它创建了一个新进程,称为子进程,它是调用进程(称为父进程)的完全相同的副本,具有相同的代码,除了少数东西(看看man fork) .如果您是父母,它将返回child process ID,如果您是孩子,则返回0,或者在失败时将-1(并设置errno)返回给父母。这是一个叉树的代码示例:

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

/*
 * I'm going to create a fork tree
 * 
 */


int main(){
    pid_t pid; /*Use it for fork() calls*/
    pid = fork(); /*Generating the first child*/
    if(pid == 0){ /*I'm the child*/
        pid_t pid_child = fork();
        if(pid_child == 0){ /*I'm the grandchild*/
            printf("I'M THE GRANDCHILD\n");
            return 0; /*Terminates the new process*/
        }else if(pid_child > 0){ /* I'm the child*/ 
            waitpid(pid_child,NULL,0);
            printf("I'M THE CHILD\n");
            return 0; /*Terminates the new process*/
        }
    }else if(pid > 0){ /*I'm the parent*/
        waitpid(pid,NULL,0); /*Waiting for the child*/
        printf("I'M THE PARENT\n");
    }
    return 0;
}

【讨论】:

  • “外甥”实际上不是原流程的孙子吗?
  • 你是对的。我不知道他们之间的区别很抱歉
猜你喜欢
  • 2023-03-22
  • 2021-07-09
  • 2014-07-20
  • 1970-01-01
  • 1970-01-01
  • 2012-03-31
  • 2021-12-15
  • 1970-01-01
  • 2014-02-11
相关资源
最近更新 更多