进程 相关系统函数

进程 相关系统函数

  • fork
  • getpid、getppid
  • 指令 ps
  • getuid、geteuid
  • getgid、getegid

fork


描述

创建一个子进程

头文件
#include <unistd.h>
函数签名
pid_t fork(void);
返回值

成功:
在父进程中返回子进程的 pid (process id)(正整数);
在子进程中返回0;
失败:
返回-1,并设置 error;

学习笔记
  1. fork 函数没有参数;
  2. 返回值:在总的说有两个,一个是在父进程,一个在子进程,子进程不会执行产生他的 fork();
  3. 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

在这里插入图片描述

学习笔记
  1. 所有主函数的父进程都是终端;

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值