#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid_t pid2;
pid = getpid();//获取当前程序的pid
printf("before fork:pid = %d\n",pid);
fork();//在当前程序里fork一个新进程
//fork ()之后下面的代码会被执行两次 一次主进程 一次子进程
pid2 = getpid();
printf("after fork:pid = %d\n",pid2);
if(pid == pid2){
printf("this is father printf\n");
}else{
printf("this is child print,child pid =%d\n",getpid());
}
return 0;
}
//通过fork()的返回值判断父子进程
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("father pid:%d\n",getpid());
pid = fork();//fork()返回0代表当前是子进程 返回非负数代表当前是父进程
if(pid>0){
printf("this is father print,father pid:%d\n",getpid());
}
else if(pid == 0){
printf("this is child print,child pid =%d\n",getpid());
}
return 0;
}```
Linux进程编程demo2创建进程函数fork的使用.c
最新推荐文章于 2025-12-06 19:52:12 发布
1230

被折叠的 条评论
为什么被折叠?



