getpid、getppid、getuid、geteuid、getgid、getegid

放肆的年华 提交于 2020-01-19 03:48:29

文字记录

getpid、getppid等等这些都是获取id信息的API

DESCRIPTION
getpid() returns the process ID (PID) of the calling process. (This
is often used by routines that generate unique temporary filenames.)
getppid() returns the process ID of the parent of the calling process.

上面是getpid和getppid的description 然后是原型

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

   pid_t getpid(void);
   pid_t getppid(void);

要注意的是pid_t是一种类型啦,按照课程讲解的话最好记录为pid type这样,容易区分。
getpid是获得当前的进程id
getppid是当前进程的父进程id

在terminal里面输入ps这个命令的话就可以显示当前的活动进程

ps displays information about a selection of the active processes.

用这个来对比测试

测试代码

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


int main(int argc ,char* argv[])
{
	if (2 != argc)
	{
		printf("usage: ./a.out password\n");
		return -1;	
	}
	else
	{
		int paswd = atoi(argv[1]);
		if (111 != paswd)
		{
			printf("password error\n");
			return -1;
		}
	}
	
	pid_t process1 = -1,process2 = -1 ;
	process1 = getpid();
	process2 = getppid();
	
	printf("process1 = %d\n",process1);
	if(-1 == process1)
	{
		perror("getpid");
	}
	printf("process1 = %d\n",process2);
	
	
	return 0;
}

代码开头加上了argc argv的使用,还有atoi的使用,权当练习啦,后面才是真的测试代码。
getpid的man手册里面error项说这个api 是always successful的,所以我后面加上了的error判断估计也没啥用。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!