Linux进程管理之一(属性获取,fork、exit的使用)

文章涉及获取当前进程ID(pid)及其父进程ID(ppid)的结构体,创建子进程(fork)的实现,并在退出进程时使用atexit注册自定义函数打印进程ID。
摘要由CSDN通过智能技术生成

第一关

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

/**********************
 * pid: 当前进程ID
 * ppid: 父进程ID
***********************/
struct procIDInfo
{
	pid_t pid;
	pid_t ppid;
};

/************************
 * 返回值: 需要被打开的目录路径
*************************/
struct procIDInfo getProcInfo()
{
	struct procIDInfo ret;   //存放进程ID信息,并返回
	/********** BEGIN **********/
	ret.pid= getpid();
    ret.ppid=getppid();
	
	/********** END **********/

	return ret;
}

第二关

#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>

/************************
 * 提示: 不要在子进程或父进程中使用exit函数或者return来退出程序
*************************/
void createProcess()
{
	/********** BEGIN **********/
	pid_t pid=fork();
 
    if(pid==-1)
    {
        printf("创建进程失败(%s)!\n", strerror(errno));
    }
	else if(!pid)
    {
        printf("Children",getpid(),getppid());
    }
    else
    {
        printf("Parent",getpid(),getppid());
    }
	
	/********** END **********/
}

第三关

#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
 
/************************
 * 提示: 用户需要在exitProcess函数中使用atexit函数注册一个自定义函数,并在自定义函数中打印出当前进程ID号
*************************/
void out()
{
    printf("%d\n",getpid());
}
void exitProcess()
{
	/********** BEGIN **********/
    if(atexit(out)!=0)
    {
        printf("调用atexit函数错误\n");
    }
}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值