头歌实践教学平台——Linux之进程管理
补全createProcess函数,使用fork函数创建进程,并在子进程中输出"Children"字符串,在父进程中输出"Parent"字符串。补全createProcess函数,使用vfork函数创建进程,并在子进程中输出"Children"字符串(提示:需要换行),在父进程中输出"Parent"字符串(提示:需要换行)。补全exitProcess函数,使用atexit函数注册一个函数,在注册函
·
目录
第1关:获取进程常见属性
补全getProcInfo函数,用于获取当前进程ID和其父进程ID(提示:将结果存放在procIDInfo结构体中)。
#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;
}
第2关:进程创建操作-fork
补全createProcess函数,使用fork函数创建进程,并在子进程中输出"Children"字符串,在父进程中输出"Parent"字符串。(注意:不要在createProcess函数中使用exit函数或者return来退出程序)。
#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("创建进程失败!");
else if(pid==0)
printf("Children");
else
printf("Parent");
/********** END **********/
}
第3关:进程创建操作-vfork
补全createProcess函数,使用vfork函数创建进程,并在子进程中输出"Children"字符串(提示:需要换行),在父进程中输出"Parent"字符串(提示:需要换行)。
#include <unistd.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
/************************
* 提示: 不要在子进程中使用return来退出程序
*************************/
void createProcess()
{
/********** BEGIN **********/
pid_t pid=vfork();
if(pid==-1)
printf("创建进程失败!\n");
else if(pid==0)
printf("Children\n");
else
printf("Parent\n");
/********** END **********/
exit(0);
}
第4关:进程终止
补全exitProcess函数,使用atexit函数注册一个函数,在注册函数中打印出当前进程的ID号。
#include <unistd.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdio.h>
/************************
* 提示: 用户需要在exitProcess函数中使用atexit函数注册一个自定义函数,并在自定义函数中打印出当前进程ID号
*************************/
void exitProcess()
{
/********** BEGIN **********/
void xiu()
{
printf("%d",getpid());
}
if(atexit(xiu)!=0)
{
printf("调用atexit函数错误!");
}
/********** END **********/
}
更多推荐



所有评论(0)