简体   繁体   English

什么时候调用fork()?

[英]When to call fork()?

I have two code samples here 我这里有两个代码示例

#include<stdio.h>
int main()
{
        int i = 0;
        i++;
        fork();
        printf("i - %d, pid - %d, addr -%p\n",i,getpid(),&i);
        return 0;
}

user@Ubuntu ~/Arena/c $ ./a
i - 1, pid - 6765, addr -0x7fffd892950c
i - 1, pid - 6766, addr -0x7fffd892950c

with my second program being 我的第二个程序是

#include<stdio.h>
int main()
{
        int i = 0;
        i++;
        printf("i - %d, pid - %d, addr -%p\n",i,getpid(),&i);
        fork();
        return 0;
}

user@Ubuntu ~/Arena/c $ ./b
i - 1, pid - 6772, addr -0x7fff39120f2c

Well as far as I know fork should create a COMPLETE copy of the parent program from top to bottom and execute it, if it is that way why is the position of fork() call making such a big difference ? 据我所知,fork应该从上到下创建父程序COMPLETE副本并执行它,如果那样,为什么fork()调用的位置会产生很大的不同? Could some one explain why is the printf omitted in my second program ? 有人可以解释为什么我的第二个程序中省略了printf吗?

fork() creates a copy of the process, and continues executing both processes at the point you call fork(). fork()创建该进程的副本,并在您调用fork()时继续执行两个进程。

So in your second example, your printf is executed before the fork when there is only one process. 因此,在第二个示例中,当只有一个进程时,将在fork之前执行printf。

Fork creates a complete copy of your program but execution continues from the point in which fork is called. Fork创建了程序的完整副本,但是从调用fork那一点开始继续执行。 Put printf after the fork and see what happens. 将fork放在printf之后,看看会发生什么。

Usually a fork call will be followed by a check if fork returned the pid of the child or not. 通常,在fork调用之后会检查一下fork返回了孩子的pid If it did, then your current running process is the parent which received the child's pid in order to be able to manage the child, if it didn't then your current running process is the child. 如果是这样,那么您当前正在运行的进程就是接收孩子的pid的父级,以便能够管理该孩子;如果没有,则您当前正在运行的进程就是该孩子。

For further enlightenment, try: 为了进一步启发,请尝试:

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    int i = 0;
    i++;
    printf("A: i - %d, pid - %d, addr -%p", i, getpid(), &i);
    fork();
    printf("\nB: i - %d, pid - %d, addr -%p\n", i, getpid(), &i);
    return 0;
}

The first printf() doesn't include a newline, so the output is held in memory. 第一个printf()不包含换行符,因此输出保留在内存中。 The second printf() includes newlines, so the output appears after the program has forked. 第二个printf()包含换行符,因此输出将在程序分叉之后出现。 You should see the same information in the two lines tagged A ; 您应该在标记为A的两行中看到相同的信息; you should see different information in the two lines tagged B . 您应该在标记为B的两行中看到不同的信息。

In a single-threaded application, the parent and child processes are almost identical except for the PID, Parent PID, and the value returned by fork() . 在单线程应用程序中,除了PID,Parent PID和fork()返回的值之外,父进程和子进程几乎相同。 For the full details, see the POSIX specification of fork() . 有关完整的详细信息,请参见fork()的POSIX规范。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM