【Linux进程】三、进程控制——fork()系统调用深度刨析_fork系统调用

  • 包含头文件
#include <sys/types.h>
#include <unistd.h>

  • 函数原型
pid\_t getpid(void);
pid\_t getppid(void);

  • 函数功能

    • getpid() returns the process ID of the calling process. 获得当前进程的ID。
    • getppid() returns the process ID of the parent of the calling process. 获得当前进程的父进程的ID。
  • 函数参数

void

  • 函数返回值

    • getpid()返回当前进程ID
    • getppid()返回当前进程的父进程ID

🥇2. fork()工作机制

🥈2.1 fork()的实现机制——一次调用两次返回与进程复制

下面通过一个案例来分析fork()是如何创建进程,又是如何返回的。

/\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*
 >File Name : fork\_test.c
 >Author : Mindtechnist
 >Company : Mindtechnist
 >Create Time: 2022年05月18日 星期三 15时59分29秒
\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc, char\* argv[])
{
	printf("=== process begin ===\n");
	pid\_t pid = fork();
	if(pid == -1)
	{
		perror("fork err");
		return -1;	
	}
	if(pid == 0) /\*子进程\*/
	{
		printf("i am child: %d, may parent: %d\n", getpid(), getppid());	
        /\* test2
 while(1)
 {
 printf("fork process\n");
 sleep(1);
 }
 \*/
	}
	if(pid > 0)
	{
		printf("i am call: %d, child: %d, parent: %d\n", getpid(), pid, getppid());	
        /\* test1
 sleep(1);
 \*/
        /\* test2
 while(1)
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值