进程 相关系统函数
- fork
- getpid、getppid
- 指令 ps
- getuid、geteuid
- getgid、getegid
fork
描述
创建一个子进程
头文件
#include <unistd.h>
函数签名
pid_t fork(void);
返回值
成功:
在父进程中返回子进程的 pid (process id)(正整数);
在子进程中返回0;
失败:
返回-1,并设置 error;
学习笔记
- fork 函数没有参数;
- 返回值:在总的说有两个,一个是在父进程,一个在子进程,子进程不会执行产生他的 fork();
- pid_t 类型表示进程 ID,但为了表示-1,它是有符号整型(0 不是有效进程 ID, init 最小,为1) ;
示例
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
int pid;
pid = fork();
if(pid == -1){
perror("process create error");
exit(1);//close the process
}
if(pid > 0){
printf("I'm parent process of %d\n", pid);
}else if(!pid){
printf("I'm child process\n");
}
sleep(1);
return 0;
}
注:
不延时的话,父进程打印完就结束了,而子进程还没打印,最后就会输出在命令行;
执行结果
getpid、getppid
描述
获取进程id
头文件
#include <sys/types.h>
#include <unistd.h>
函数签名
pid_t getpid(void);
pid_t getppid(void);
返回值
getpid:
返回调用进程的id;
getppid:
返回调用进程的父进程的id;
学习笔记
这两个函数(getpid、getppid)不会失败;
示例
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
int main(){
int pid;
pid = fork();
if(pid == -1){
perror("process create error");
exit(1);//close the process
}
if(pid > 0){
printf("My process id is %d. I'm the parent process of %d\n",
getpid(), pid);
}
if(!pid){
printf("My process id is %d. I'm the child process of %d.\n",
getpid(), getppid());
}
sleep(5);
return 0;
}
运行结果
疑问
有时,会在命令行输出??why??
加 sleep延时保证父进程最后结束
打印进程信息
ps -ajx
第一列为父进程 id
ps -ajx | grep fork_getid
grep fork_getid:定位到 fork_getid
显然进程 12757的父进程 为 2610,这是啥?当前终端(bash);
ps -aux
第一列:用户名、第二列: 进程id;
ps -aux | grep fork_getid
学习笔记
- 所有主函数的父进程都是终端;
getuid
NAME
getuid, geteuid - get user identity
SYNOPSIS
#include <unistd.h>
#include <sys/types.h>
uid_t getuid(void);
DESCRIPTION
getuid() returns the real user ID of the calling process.
geteuid() returns the effective user ID of the calling process.
ERRORS
These functions are always successful.
getgid
NAME
getgid, getegid - get group identity
SYNOPSIS
#include <unistd.h>
#include <sys/types.h>
gid_t getgid(void);
gid_t getegid(void);
DESCRIPTION
getgid() returns the real group ID of the calling process.
getegid() returns the effective group ID of the calling process.
ERRORS
These functions are always successful.
2020/07/24 9:35
@luxurylu