您的位置:首页 > 运维架构 > Linux

Linux系统编程:fork函数的使用【循环创建N个子线程】

2018-03-11 10:08 721 查看

fork函数介绍

在linux下面进行系统编程,一定要养成一个好习惯,不懂的函数 直接 找男人,用man 指令进行查看,虽然是全英文 但是要强迫自己 学会看英文文档!下面是介绍,我们看重点。FORK(2) Linux Programmer's Manual FORK(2)

NAME
fork - create a child process

SYNOPSIS
#include <unistd.h>

pid_t fork(void);

DESCRIPTION
fork() creates a new process by duplicating the calling process. The new process is referred to as the child process. The calling
process is referred to as the parent process.

The child process and the parent process run in separate memory spaces. At the time of fork() both memory spaces have the same
content. Memory writes, file mappings (mmap(2)), and unmappings (munmap(2)) performed by one of the processes do not affect the
other.
RETURN VALUE
On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in
the parent, no child process is created, and errno is set appropriately.
我们重点看RETURN VALUE ,大致意思是 子进程创建成功 将子进程的PID 返回给父进程,且将0 返回给子进程!就是所fork 函数有2个返回值。因为fork成功会有新的子进程产生,和父进程在此处一起往下继续执行并抢占资源。这个能理解,那么创建循环换创建N个子进程 就手到擒来了。

循环创建N个子进程代码

代码很简单,为了让进程按顺序打印给每个进程加了一个sleep。getpid函数是获取当前进程的pid,getppid是获取当前进程的父进程的pid。#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
int i;
pid_t pid;
for(i = 0; i < 5;i++)
{

pid = fork();
//子进程就退出循环,父进程继续创建子进程
if(pid == 0)
{
break;
}
}
if(i < 5)
{
sleep(i);
printf("I'm child thread %d,pid=%d,ppid=%d\n",i+1,getpid(),getppid());
}else
{
sleep(i);
printf("I'm parent thread,pid=%d,ppid=%d\n",getpid(),getppid());
}

return 0;

}

运行结果

可以看到,我们的main函数主进程 也是有父进程的,是bash进程,bash进程运行我们的可执行程序,然后创建main进程。

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: