Linux Process_control

本文详细介绍了Linux下的进程控制,包括进程标识pid、fork、wait和waitpid、exec、用户标识、进程调度、进程关系(如进程组、session、controlling Terminal和job control)等内容,还讲解了shell如何执行程序。
摘要由CSDN通过智能技术生成

进程标识pid

id=0的是调度进程(swapper),该进程是内核的一部分,并不执行磁盘的任何的程序,也被称为系统进程
id=1 是init进程,属于用户态进程,但是以超级用户特权运行,是所有孤儿进程的父进程

#include <unistd.h>
pid_t getpid(void);
Returns: process ID of calling process
pid_t getppid(void);
Returns: parent process ID of calling process
uid_t getuid(void);
Returns: real user ID of calling process
uid_t geteuid(void);
Returns: effective user ID of calling process
gid_t getgid(void);
Returns: real group ID of calling process
gid_t getegid(void);
Returns: effective group ID of calling process

#include <unistd.h>
int setuid(uid_t uid);
int setgid(gid_t gid);
Both return: 0 if OK, −1 on error

#include <unistd.h>
int setreuid(uid_t ruid, uid_t euid);
int setregid(gid_t rgid, gid_t egid);
Both return: 0 if OK, −1 on error

fork

#include <unistd.h>
pid_t fork(void);
Returns: 0 in child, process ID of child in parent, −1 on error

fork函数调用一次,返回两次,其中返回0是child进程,pid>0则是子进程的pid.内核一般保存父进程的区域堆栈,数据段的完全副本,且副本的访问权限只读,父进程或者子进程试图修改的话,内核就会建立修改区域的副本,(Copyy-On-Write)

在这里插入图片描述

wait and waitpid

#include <sys/wait.h>
pid_t wait(int *statloc);
pid_t waitpid(pid_t pid, int *statloc, int options);
/* Wait for a child to die. When one does, put its status in *STAT_LOC
and return its process ID. For errors, return (pid_t) -1.

This function is a cancellation point and therefore not marked with
__THROW. */
extern __pid_t wait (int *__stat_loc);


void tl::testProcess(){
   

	auto preStatus = [](int status)->void {
   
		if (WIFEXITED(status))
			printf("normal termination, exit status = %d\n",
				WEXITSTATUS(status));
		else if (WIFSIGNALED(status))
			printf("abnormal termination, signal number = %d%s\n",
				WTERMSIG(status),
#ifdef WCOREDUMP
				WCOREDUMP(status) ? " (core file generated)" : "");
#else
			"");
#endif
		else if (WIFSTOPPED(status))
			printf("child stopped, signal number = %d\n",
				WSTOPSIG(status));

	};

	pid_t pid;
	int status;
	if ((pid = fork()) < 0) {
   
		err_sys("fork error");
	}
	else if (pid == 0) /* child */
		exit(7);

	if (wait(&status) != pid) /* wait for child */
		err_sys("wait error");
	preStatus(status); /* and print its status */
	if ((pid = fork()) < 0) {
   
		err_sys("fork error");
	}
	else if (pid == 0) /* child */
		abort(); /* generates SIGABRT */
	if (wait(&status) != pid) /* wait for child */
		err_sys
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值