进程

进程

进程(Process)是系统进行资源分配和调度的基本单位,线程是任务调度的最小单位

Linux下可以使用top命令查看系统进程运行情况

进程ID

每个进程都有一个唯一的标识符,进程ID简称为PID

  • 进程ID默认的最大值为32768,虽然PID可以修改,但是一般不这样操作,因为进程ID的分配是线性的
  • 除了init进程,其它进程都是被其它进程创建的;创建进程的进程称为父进程,被创建的进程称为子进程

获取进程ID

//getpid可以获取进程ID
//getppid可以获取进程父进程的ID

#include <sys/types.h>
#include <unistd.h>

pid_t getpid(void);		//获取进程ID
pid_t getppid(void);	//获取父进程ID

函数使用实例:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
		pid_t pid,ppid;
		
		pid = getpid();
		ppid = getppid();

		printf("The process pid is: %d \n",pid);
		printf("The process ppid is: %d \n",ppid);
		return 0;
}

exec函数

Linux中,可以使用exec族函数将程序载入内存,在一个可执行程序中运行其它的可执行程序

//头文件
#include <unistd.h>

//l、p表示以列表形式还是数组形式调用参数
//p表示函数的第一个参数为文件绝对路径
//e表示提供新的环境变量
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[]);

函数实例:

#include <stdio.h>
#include <unistd.h>

int main()
{
		if(execl("/home/linuxsystemcode/process/getpid","getpid",NULL) < 0)
			printf("The exec failed!\n");

		return 0;
}

fork函数创建子进程

fork系统调用用于创建一个新的进程,称为子进程。它与进程(调用fork的进程)同时运行,此进程称为父进程。创建完新的进程之后,二者将共同执行fork()系统调用之后的下一条指令

  • 子进程和父进程使用相同的PC(程序计数寄存器),相同的CPU寄存器
//头文件
#include <unistd.h>

pid_t fork(void);
//函数执行成功,返回两个值:子进程pid(父进程),0(子进程)
//函数执行失败:返回-1,只有当内存耗尽或pid用尽的情况下fork()会失败,一般不会发生

函数使用实例:

#include <stdio.h>
#include <unistd.h>

int main()
{
		pid_t pid;
		pid = fork();
		if(pid == 0)
				printf("This is Child!\n");
		else
				printf("This is Father!\n");
				sleep(1);				//防止父进程在没有调用子进程之前结束

		return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章