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进程。相关文章推荐
- [Linux进程]使用fork函数创建多个子进程
- Linux系统下C语言编程:线程的创建和使用
- Linux系统中C语言编程创建函数fork()执行解析
- linux系统编程之进程(七):system()函数使用
- Linux中使用C语言的fork()函数创建子进程的实例教程
- linux下c编程系统调用之有名管道FIFO函数的使用及案例
- Linux系统编程—— fork() 函数详解
- linux系统编程之进程(五):exec系列函数(execl,execlp,execle,execv,execvp)使用
- 8.17_Linux之bash shell脚本编程入门篇(三)之循环以及函数function的使用
- 【Linux系统编程】线程堆栈大小的使用介绍
- 简单掌握Linux系统中fork()函数创建子进程的用法
- linux系统编程之进程(八):守护进程详解及创建,daemon()使用
- Linux下C编程,子进程创建函数fork() 执行解析
- 使用C语言的fork()函数在Linux中创建进程的实例讲解
- Linux下的多进程编程(转) - fork(),exec()等函数的使用[zz]
- linux系统编程之进程(八):守护进程详解及创建,daemon()使用
- linux系统编程之进程(四):wait/waitpid函数与僵尸进程、fork 2 times
- Delphi中使用Win32 API创建内建消息循环的线程函数
- linux系统编程之进程(八):守护进程详解及创建,daemon()使用
- Linux系统进程控制编程(一)————基本概念和函数getpid的使用