1.touch myprocess.c
2.ls > Makefile
3.vim Makefile
myprocess:myprocess.c
gcc -o myprocess myprocess.c
.PHONY:clean
clean:
rm -f myprocess
4.创建子进程 make fork
6.查看fork手册 man fork(如果创建成功,返回子进程id ,父进程0;如果创建失败,返回-1)
5.vim myprocess.c 并且创建子进程
#include<stdio.h>
#include<unistd.h>
int main()
{
pid_t id = fork();
return 0;
}
~
- 获取子进程id和父进程id;getpid() getppid()
#include<stdio.h>
#include<unistd.h>
int main()
{
pid_t id = fork();
if(id < 0)
{
perror("fork");
return 1;
}
else if(id == 0)
{
//child
while(1)
{
printf("我是子进程,pid: %d, ppid: %d\n", getpid(), getppid());
sleep(1);
}
}
else
{
//parent
while(2)
{
printf("我是父进程, pid: %d, ppid: %d\n", getpid(), getppid());
sleep(3);
}
}
return 0;
}
7.make一下,生成myprocess运行文件,然后./myprocess
ppid:9101是bash,也就是命令行解释器
8.清除myprocess运行文件: make clean