linux中的fork函数

fork函数简介

作用

创建一个子进程。

原型

pid_t fork(void)

返回值

失败返回-1;成功返回:① 父进程返回子进程的ID    ②子进程返回 0

pid_t类型表示进程ID,但为了表示-1,它是有符号整型。(0不是有效进程ID,init最小,为1)

(注意返回值,不是fork函数能返回两个值,而是fork后,fork函数变为两个,父子需【各自】返回一个。)

创建一个子进程

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

int count = 100;

int main(int argc, const char* argv[])
{
        pid_t pid;

        printf("start: 
");
        pid = fork();
        if(pid > 0)
        {
                printf("I am a parent process, count = %d, pid = %d
", count,getpid());
                count += 10;
                printf("I am a parent process, count = %d, pid = %d
", count,getpid());
        }
        else if(pid == 0)
        {
                printf("I am a child process, count = %d, pid = %d
", count,getpid());
                count += 1;
                printf("I am a child process, count = %d, pid = %d
", count,getpid());
        }
        printf("finish!
");
        return 0;
}
View Code

循环的创建多个兄弟子进程

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

int count = 100;

int main(int argc, const char* argv[])
{
        pid_t pid;
        int i = 0;
        int n = 2;

        for(; i < n; i++)
        {
                pid = fork();
                if(pid == 0)
                {
                        break;
                }
        }

        if(i == 0)
        {
                printf("I am the first child process, pid = %d
", getpid());
        }
        else if(i == 1)
        {
                printf("I am the second child process, pid = %d
", getpid());
        }
        else if(i == 2)
        {
                printf("I am the parent process, pid = %d
", getpid());
        }
        else
        {
                printf("error
");
        }

        return 0;
}
View Code
原文地址:https://www.cnblogs.com/xumaomao/p/13056192.html