2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > Linux系统编程_进程 获取getpid(子) getppid(父) 创建(fork vfork)

Linux系统编程_进程 获取getpid(子) getppid(父) 创建(fork vfork)

时间:2022-09-29 06:26:52

相关推荐

Linux系统编程_进程 获取getpid(子) getppid(父) 创建(fork vfork)

获取进程ID

特殊说明:这些进程仅仅是在Linux下的进程

每个进程都有一个整型的IDPID每个进程都有一个父进程PPID

一个进程想控制其他进程,想与其他进程通信,需要ID

获取自己的ID

#include <sys/types.h>

#include <unistd.h>

pid_t getpid(void);

pid_t getpid(void);

功能:获取自己的进程ID

参数:

返回值:本进程的ID

获取自己的父进程的ID

#include <sys/types.h>

#include <unistd.h>

pid_t getppid(void);

pid_t getpid(void);

功能:获取自己的父进程ID

参数:

返回值:本进程的父进程的ID

创建一个进程

#include <unistd.h>

pid_t fork(void);

功能:创建一个子进程

参数:

返回值:有两次,子进程返回0,父进程返回子进程的进程号。

注意:子进程从fork函数之后执行,fork完全拷贝了父进程的地址空间给子进程,父子进程运行顺序不确定。

有两种拷贝:1.全拷贝

2.写实拷贝,当子进程里对变量进行操作时是写时拷贝

虚拟创建进程

#include <sys/types.h>

#include <unistd.h>

pid_t vfork(void);

功能:创建一个子进程

参数:

返回值:有两次,子进程返回0,父进程返回子进程的进程号。

注意:子进程从vfork函数之后执行,子进程有自己的ID与父进程共享资源,子进程先执行,父进程后执行。价值并不大,不能实现任务并发执行

与fork的区别:

1.关键区别一:

vfork直接使用父进程存储空间,不拷贝,此时子进程改变同一变量时,相应父进程使用该变量时是子进程已改变后的变量了。

2.关键区别二:

vfork保证子进程先运行,当子进程调用exit退出后,父进程才会执行。

接下来是代码内容:

1.getpid()

#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){pid_t pid;//获取当前进程的PID号pid = getpid();printf("my pid is %d\n",pid);while(1);//保持进程不退出return 0;}

2.这个是父子进程的浅浅执行方式

#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){pid_t pid;pid_t pid2;pid = getpid();printf("before fork: pid = %d\n",pid );//父进程的PID号fork(); //fork后创建子进程,并执行fork之后的代码两次,一次是父进程执行,还有一次是子进程执行pid2 = getpid(); //父子进程都各自getpid给pid2printf("after fork: pid = %d\n",pid2 );if(pid == pid2){printf("this is father print\n");}else{printf("this is child print,child pid = %d\n",getpid());}return 0;}

3.在父子进程中如何操作

#include <stdio.h>#include <sys/types.h>#include <unistd.h>int main(){pid_t pid;printf("father: id=%d\n",getpid());pid = fork();//fork之后会有两个pid,一个是父进程的,一个是子进程的if(pid > 0){printf("this is father print, pid = %d\n",getpid());//这个是获取父进程的pid号printf("%d\n",(int)pid);//这个pid==子进程的pid号}else if(pid == 0){printf("this is child print,child pid = %d\n",getpid());//这个获取的子进程的pid号}return 0;}

4.vfork的代码验证:(也是创建了两进程),但先进行的是子进程的内容

#include <stdio.h>#include <stdio.h>#include <sys/types.h>#include <unistd.h>#include <stdlib.h>//exit的头文件int main(){pid_t pid;int cnt = 0;pid = vfork();if(pid > 0){while(1){printf("cnt=%d\n",cnt);printf("this is father print, pid = %d\n",getpid());sleep(1);}}//子进程:else if(pid == 0){while(1){printf("this is chilid print, pid = %d\n",getpid());sleep(1);cnt++;if(cnt == 3){exit(0);//调用exit,exit里面必须有参数break;}}}return 0;}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。