概要:
-
使用fork函数创建一个进程:
- pid_t fork(void);
-
fork函数调用成功,返回
- 返回值0,代表当前进程是子进程
- 返回值非负数,代表当前进程为父进程
-
调用失败,返回-1
code:demo5.c
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t retpid;
pid_t pid;
pid=getpid();//fork之前和之后的区别
retpid=fork();
//pid=getpid();//fork之前和之后的区别
if(retpid > 0){
printf("father pid each run one,pid=%d\n",pid);
}
else if(retpid == 0){
printf("child pid each run one,pid=%d\n",pid);
}
return 0;
}
fork之前,运行结果:
CLC@Embed_Learn:~/LinuxLearn/PID$ ./a.out
father pid each run one,pid=43357
child pid each run one,pid=43357
fork之后,运行结果:
CLC@Embed_Learn:~/LinuxLearn/PID$ ./a.out
father pid each run one,pid=43401
child pid each run one,pid=43402
code:demo5.c
- (把fork返回值打印出来:可以发现
父进程的fork返回值==子进程的pid)
运行结果:
CLC@Embed_Learn:~/LinuxLearn/PID$ ./a.out
father pid each run one,pid=43557,retpid=43558
child pid each run one,pid=43558,retpid=0
第四节: 旧的和新的创建方式