文章目录
进程标识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