Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
398 views
in Technique[技术] by (71.8m points)

c - What exactly does fork return?

On success, the PID of the child process is returned in the parent’s thread of execution, and a 0 is returned in the child’s thread of execution.

p = fork();

I'm confused at its manual page,is p equal to 0 or PID?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm not sure how the manual can be any clearer! fork() creates a new process, so you now have two identical processes. To distinguish between them, the return value of fork() differs. In the original process, you get the PID of the child process. In the child process, you get 0.

So a canonical use is as follows:

p = fork();
if (0 == p)
{
    // We're the child process
}
else if (p > 0)
{
    // We're the parent process
}
else
{
    // We're the parent process, but child couldn't be created
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...