一、编写程序pro1.c,在程序中创建一个子进程,使父子进程分别打印不同的内容,父进程换行打印“This is parent process”,子进程换行打印“This is child process”。
- 创建.c文件,命名为pro1.c,向里面添加以下代码:
linux命令行文本编辑器真的很low,建议使用外部编辑器编辑,编辑好后然后上传保存到工作目录,然后命令行编译运行。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork(); //调用fork()函数创建子进程
if (pid == -1) //创建失败
{
perror("fork error");
exit(1); //退出进程,指定返回值1
}
else if (pid > 0) //父进程
{
printf("This is parent process\n");
}
else if (pid == 0) //子进程
{
printf("This is child process\n");
}
printf("........finish..........\n");
return 0;
}
- 将生成的C语言源文件编译成二进制可执行文件.o。
$gcc -o pro1.o pro1.c
若运行失败,先安装gcc编辑器:$yum -y install gcc
- 运行pro1.o
$./pro1.o
二、编写程序pro2.c,在程序中创建一个子进程,使子进程通过exec更改代码段,执行cat命令。父进程换行打印“parent process:”及父进程id,子进程换行打印“child process:”及子进程id,另外子进程还要打印出“cat -b pro2.c”
- 创建pro2.c文件,添加以下代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork();
if (pid == -1)
{
perror("fork error");
exit(1);
}
else if (pid > 0)
{
printf("parent process:pid=%d\n", getpid());
}
else if (pid == 0)
{
printf("child process:pid=%d\n", getpid());
//execl("/bin/cat","-b","pro2.c",NULL); //①
//execlp("cat","-b","pro2.c",NULL); //②
char *arg[] = { "-b", "pro2.c", NULL }; //③
execvp("cat", arg);
perror("error exec\n");
printf("child process:pid=%d\n", getpid());
}
return 0;
}
- 编译运行