## 进程环境
shell下env可以查看当前环境变量
libc中定义了全局变量environ指向环境变量表,environ没有包含在任何头文件里面,所以之前要用extern声明
#include <stdio.h>
int main(void)
{
extern char **environ;
int i;
for(i=0; environ[i] != NULL; i++)
printf("%s\n", environ[i]);
return 0;
}
用environ指针可以查看所有环境变量字符串,但是不够方便,如果给出name要在环境变量
表中查找它对应的value,可以用getenv函数。
#include <stdlib.h>
char *getenv(const char *name);
getenv的返回值是指向value的指针,若未找到则为NULL。
修改环境变量可以用以下函数
#include <stdlib.h>
int setenv(const char *name, const char *value, int rewrite);
void unsetenv(const char *name);
putenv和setenv函数若成功则返回为0,若出错则返回非0。
setenv将环境变量name的值设置为value。如果已存在环境变量name,那么
若rewrite非0,则覆盖原来的定义;
若rewrite为0,则不覆盖原来的定义,也不返回错误。
unsetenv删除name的定义。即使name没有定义也不返回错误。
例 修改环境变量
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
printf("PATH=%s\n", getenv("PATH"));
setenv("PATH", "hello", 1);
printf("PATH=%s\n", getenv("PATH"));
return 0;
}
##进程运行状态
修改进程资源限制,软限制可改,最大值不能超过硬限制,硬限制只有root用户可以修改
#include <sys/time.h>
#include <sys/resource.h>
int getrlimit(int resource, struct rlimit *rlim);
int setrlimit(int resource, const struct rlimit *rlim);
查看进程资源限制
cat /proc/self/limits
ulimit -a
####进程原语
1.fork
#include <unistd.h>
pid_t fork(void);
2.exec
调用成功则加载新的程序从启动代码开始执行,不再返回,如果调用出错
则返回-1,所以exec函数只有出错的返回值而没有成功的返回值
#include <unistd.h>
extern char **environ;
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg, ..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],char *const envp[]);
3.wait/waitpid
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int *status); //status接收退出值
pid_t waitpid(pid_t pid, int *status, int options);
< -1 回收指定进程组内的任意子进程
-1 回收任意子进程
0 回收和当前调用waitpid一个组的所有子进程
>0 回收指定ID的子进程
僵尸进程:子进程退出,父进程没有回收子进程资源(PCB),则子进程变成僵尸进程
孤儿进程:父进程先于子进程结束,则子进程成为孤儿进程,子进程的父进程成为1号进程init进程,称为init进程领养孤儿进程