linux环境变量继承父进程,Linux启动程序systemd和环境变量

昨天看到一篇文章,讲的是Linux的开机启动,个人感觉写得非常好。我是在学习环境变量时看到的,所以只翻译其中的一小部分,再结合环境变量讲一讲。建议大家好好读一下原文。

systemd

Linux系统的开机流程(boot process)的结束:选定的系统核(kernel)加载到内存,然后解压自己,加载systemd,此时控制权交给了systemd,开始系统的启动流程(startup process)。

截至上面的步骤完成,只有核和systemd在运行,什么都做不了,需要systemd去完成接下来的工作,完成时Linux主机才会是可用状态。

systemd是所有进程的父进程或者祖先进程,它的pid是1。第一步,它会加载定义在/etc/fstab中的文件系统,加载后就可以访问位于/etc中的配置文件,它的配置文件/etc/systemd/system/default.target会告诉它该使用哪个target去完成接下来的工作。

target和service是systemd中的基本单元。target是一组service的组合,选择某个target后就要去启动相应的一些服务。

target的作用就是定义启动方式。举例来说,想在启动后进入图形界面模式,target就选择graphical.target,想在启动后进入命令行模式,target就选mutil-user.target,分别对应旧版本/etc/inittab文件中的level5和level3。

target对应一系列服务,我们自定义systemd服务时需要定义/usr/lib/systemd/system/myservice.service文件,在[Install]中要用WantedBy=来定义该服务用于哪个target。当target对应的所有服务都启动起来之后,Linux系统就处于那个target level了。

环境变量

“In all Unix and Unix-like systems, each process has its own separate set of environment variables. By default, when a process is created, it inherits a duplicate environment of its parent process, except for explicit changes made by the parent when it creates the child.”—来自维基百科

从上面可以看到,环境变量是和进程相关的,子进程可以继承父进程的环境变量,也可以显式地指定自己的环境变量,子进程设置的环境变量不会影响父进程的环境变量。

shell的环境变量也是shell的进程的环境变量,在shell中运行程序时,那些程序的进程是shell进程的子进程,会继承shell进程的环境变量。

因为systemd是所有进程的父进程或祖先进程(ancestor process),所以它的环境变量会被所有的进程所继承,systemd进程的环境变量可以在/etc/systemd/system.conf设置,语法为DefaultEnvironment=,DefaultEnvironment="test=test"会添加值为test的环境变量test。当我们自己添加系统服务时,也可以在/etc/systemd/system/myservice.service.d中以.conf结尾的文件(一般来说是override.conf,可以直接用systemctl edit mysevice打开)中为需要启动的服务进程指定环境变量,语法为Environment=,或者EnvironmentFile=,后一种方法会指定环境变量文件,适合需要设置比较多的环境变量的情况。

"/etc/environment is not a global configuration file.

It applies only on Linux; only to PAM sessions, as employed by login and so forth; and only in the case where a particular PAM plug-in is installed and enabled on the system, and where that PAM plug-in has not been configured to use some other file (because /etc/environment is merely its default if it is not told otherwise). It is that PAM plug-in that reads it.

Otherwise, it is just a meaningless file in /etc that nothing uses."以后遇到了再更新

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值