Linux进程
来源:互联网 发布:淘宝宝贝销量查询工具 编辑:程序博客网 时间:2024/06/03 02:25
一:进程:由进程控制块,程序段,数据段三部分组成。
进程ID是一个进程的基本属性,就是相当于我们的身份证一样,由进程ID用户可以精确的定位一个进程。
进程标识符pt_t,本质是一个无符号整型,一个进程标识符唯一对应一个进程,多个进程标识符可以对应一个程序。程序是指可运行的二进制的代码文件,这种文件加载到内存中运行就得到了一个进程,同一个文件加载多次就得到了不同的进程。
所有的进程ID存储在内核中的数据结构中,Linux提供了一些函数访问ID
getpid()和getppid()分别访问子进程和父进程,头文件是#include<unistd.h>
getuid()和geteuid()是得到进程用户ID和有效用户ID
两个函数都是失败返回-1;
代码实现打印当前进程ID
1 #include<iostream>
2 #include<stdio.h>
3 #include<unistd.h>
4 using namespace std;
5
6 int main()
7 {
8 pid_t pid,ppid,uid,euid;
9
10 pid = getpid();
11 ppid = getppid();
12 uid = getuid();
13 euid = geteuid();
14
15 printf("pid :%u\n",pid);
16 printf("ppid:%u\n",ppid);this is prent,pid :2788
this is child,pid:4672
17 printf("uid:%u\n",uid);
18 printf("euid:%u\n",euid);
19 }
二:创建一个进程
进程是系统中基本的执行单位,Linux系统中,子进程创建之后,独立于父进程,。
在Linux中用fork()创建一个新进程
#include<unistd.h>
pid_t fork(void);
除了0号进程是系统自己创建之外,所有的进程都是fork创建,,创建新进程的时候,调用到fork的是父进程,新创建的进程是子进程。
对于fork()函数来说,不需要参数,返回值是一个进程ID。对于返回值,有三种情况:
1.对于父进程来说,fork函数返回新创建的子进程的ID;
2.对于子进程来说,fork函数返回0,由于0进程是内核进程,所以子进程的程序号不可能是0;
3.如果出错,返回-1;
函数fork创建完新进程后,会将父进程中的内容复制到子进程的空间中,包括父进程的数据段和堆栈段,并且和父进程共享代码段。Fork函数会返回两次,一次是在父进程中返回,另外一次是在子进程中返回,但是两次的返回值是不一样的;
#include<stdio.h>
2 #include<unistd.h>
3 #include<stdlib.h>
4 int main()
5 {
6 pid_t pid;
7 pid = fork();
8 if(pid<0)
9 {
10 printf("Error\n");
11 exit(1);
12 }
13 else if(pid == 0)
14 printf("this is child,pid:%u\n",getpid());
15 else
16 {
17 printf("this is prent,pid :%u\n",getppid() );
18 }
19 return 0;
20
21 }
结果是:
this is prent,pid :2788
this is child,pid:4672
由此可以看出,子进程和父进程是平等的,先执行哪一个取决于系统的调度算法。
三:父子进程的共享资源
子进程完全复制了父进程的地址内容,包括堆栈段和数据段的内容,子进程和父进程共享代码段,原因是子进程可能会执行不同的流程,会改变数据段和堆栈段,然而代码段是只读的,不会被修改,所以父子可以共用代码段。
代码实现说明:
1 #include<iostream>
2 #include<stdio.h>
3 #include<stdlib.h>
4 #include<unistd.h>
5 using namespace std;
6
7 int global; //数据段,全局变量
8 int main()
9 {
10 pid_t pid;
11 int stack = 1; //栈中,局部变量
12 int *heap;
13 heap = (int *)malloc(sizeof(int)); //堆中
14 *heap = 2;
15 pid = fork();
16 if(pid<0)
17 {
18 printf("Error\n");
19 exit(1);
20 }
21 else if(pid == 0)
22 {
23 global++;
24 stack++;
25 (*heap)++;
26
27printf("the child,data:%d,stack:%d,heap:%d\n",global,stack,*heap);
28 exit(0); //子进程结束
29 }
30 sleep(2);
31 printf("the parent,data:%d,stack:%d,heap:%d\n",global,stack,*heap);
32 return 0;
结果:
the child,data:1,stack:2,heap:3
the parent,data:0,stack:1,heap:2
说明了父子进程之间相互不影响。
- Linux--进程--僵尸进程
- linux 进程
- linux 进程
- Linux 进程
- Linux进程
- LINUX进程
- Linux进程
- Linux进程
- Linux进程
- linux进程
- Linux进程
- 进程-Linux
- linux-进程
- Linux进程
- linux 进程
- linux进程
- linux进程
- Linux进程
- go语言的延迟队列客户端
- 【51单片机学习过程记录】5数码管静态显示
- mybatis 和 hibernate 的区别
- MatLab程序基础
- iOS开发 Method Swizzling 可以调换两个方法
- Linux进程
- 并发 并行 同步 异步 多线程的区别
- 实现返回字符串中最长数字串函数
- 华为网络设备常用命令
- UVA 10815 set
- Android Studio JNI生成so库
- Linux进程间通信(五)
- html5圆形渐变
- 【Qt开发】布局控件之间的间距设置