0
点赞
收藏
分享

微信扫一扫

Linux编程:getpid与getppid

楚木巽 2022-04-21 阅读 54
linux

getpid用于得到当前进程的id

getppid用于得到当前进程的父进程的id

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

int main()
{	
	pid_t pid = fork();
	if(pid < 0)
	{//fork failed
		printf("fork failed");		
	}
	else if(pid == 0)
	{//in child
		printf("child id:%u parent id:%u\n", getpid(), getppid());
		exit(0);
	}
	else
	{//in parent
		printf("parent id:%u child id:%u\n", getpid(), pid);
		waitpid(pid, 0, 0);
	}
	return 0;
}

运行程序输出:
parent id:210557 child id:210558
child id:210558 parent id:210557

可见在父子进程都可以获得对方的id
举报

相关推荐

0 条评论