实验二:进程控制(8学时)
实验要点:
了解系统调用fork()、exec()和wait()的功能和实现过程。
实验内容:
- 编写一段程序,使用系统调用fork()来创建两个子进程,并由父进程重复显示字符串“parent:”和自己的标识数,而子进程则重复显示字符串“child:”和自己的标识数。
1.1创建process_sample.c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main() {
pid_t pid1, pid2;
// 创建第一个子进程
pid1 = fork();
int i=0;
// 如果是父进程
if (pid1 > 0) {
for(i=0;i<5;i++) {
printf("parent: %d\n", getpid());
}
}
// 如果是第一个子进程
else if (pid1 == 0) {
for(i=0;i<5;i++) {
printf("child 1: %d\n", getpid());
}
}
// 创建第二个子进程失败
else {
perror("fork");
return 1;
}
// 如果是父进程
if (pid1 > 0) {
// 创建第二个子进程
pid2 = fork();
// 如果是父进程
if (pid2 > 0) {
for(i=0;i<5;i++) {
printf("parent: %d\n", getpid());
}
}
// 如果是第二个子进程
else if (pid2 == 0) {
for(i=0;i<5;i++) {
printf("child 2: %d\n", getpid());
}
}
// 创建第二个子进程失败
else {
perror("fork");
return 1;
}
}
return 0;
}
这个程序创建了两个子进程,每个进程都输出相应的字符串和进程标识号。
1.2编译process_sample.c
1.3运行process_sample
父进程重复显示字符串“parent:”和自己的标识数10976
子进程1重复显示字符串“child1:”和自己的标识数10977
子进程1重复显示字符串“child2:”和自己的标识数10978
- 编写一段程序,使用系统调用fork()来创建一个子进程。子进程通过系统调用execvp()更换自己的执行代码,新的代码显示“new program.”。而父进程则调用wait()等待子进程结束,并在子进程结束后显示子进程的标识符,然后正常结束。
2.1创建process_sample2.c文件
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
pid_t pid;
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
// 子进程
if (pid == 0) {
// 使用 execvp 更换执行代码
char *args[] = {"echo", "new program.", NULL};
execvp("echo", args);
// 如果 execvp 失败
perror("execvp");
exit(EXIT_FAILURE);
}
// 父进程
else {
// 等待子进程结束
wait(NULL);
// 显示子进程的标识符
printf("Child process ID: %d\n", pid);
}
// 正常结束
return 0;
}
2.2编译
2.3 执行结果
输出new program
子进程标识符11194
流程图如下所示