linux——fork的使用,创建进程函数

使用fork函数创建一个进程

#include <unistd.h>

pid_t fork(void);

fork函数调用成功,返回两次

返回值为0,代表当前进程是子进程

返回值为非负数,代表当前进程为父进程

调用失败,返回-1

1、代码演示:

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

int main()
{
	pid_t pid;
	pid=getpid();
	
	fork();
	printf("my pid is %d,current pro id:%d\n",pid,getpid());

	return 0;
}

运行结果:

my pid is 21536,current pro id:21536
my pid is 21536,current pro id:21537

fork函数之后,程序运行了两遍,一遍为父进程运行的,一遍为子进程运行的。

两个pid号一致的为父进程,pid号不一致的为子进程

2、修改代码,做出判断,两个进程分别运行

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

int main()
{
	pid_t pid;
	pid=getpid();
	
	fork();

	if(pid==getpid()){
		printf("this is father print\n");
	}
	else{
		printf("this is child print,pid=%d\n",getpid());
	}

	printf("my pid is %d,current pro id:%d\n",pid,getpid());

	return 0;
}

编译运行得出结果:

this is father print
my pid is 21584,current pro id:21584
this is child print,pid=21585
my pid is 21584,current pro id:21585

3、进一步修改:

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

int main()
{
	pid_t pid;
	pid_t pid2;
	pid=getpid();
	printf("before fork:pid=%d\n",pid);
	
	fork();
	
	pid2=getpid();
	printf("after fork:pid=%d\n",pid2);

	if(pid==pid2){
		printf("this is father print\n");
	}
	else{
		printf("this is child print,pid=%d\n",getpid());
	}

	return 0;
}

编译运行结果:

before fork:pid=21662
after fork:pid=21662
this is father print
after fork:pid=21663
this is child print,pid=21663

4、fork返回值判断父进程、子进程

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

int main()
{
	pid_t pid;
	
	printf("father pid=%d\n",getpid());

	pid=fork();
	

	if(pid>0){
		printf("this is father print\n");
	}
	if(pid==0){
		printf("this is child print,pid=%d\n",getpid());
	}

	return 0;
}

编译运行结果:

father pid=21716
this is father print
this is child print,pid=21717

5、fork的返回值打印,演示代码

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

int main()
{
	pid_t pid;
	pid_t pid2;
	pid_t retpid;

	pid=getpid();
	printf("before fork:pid=%d\n",pid);
	
	retpid=fork();
	
	pid2=getpid();
	printf("after fork:pid=%d\n",pid2);

	if(pid==pid2){
		printf("this is father print%d\n",retpid);
	}
	else{
		printf("this is child print,%d,pid=%d\n",retpid,getpid());
	}

	return 0;
}

编译运行结果:

before fork:pid=21855
after fork:pid=21855
this is father print21856
after fork:pid=21856
this is child print,0,pid=21856

子进程返回值是0,父进程返回值是子进程pid号

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值