第三次作业是学习进程管理,笔者竟然没有学习明白,课下还需要不断翻书回看才是。第三次作业一共两个实验
实验目的
进一步学习Linux中与进程和线程控制相关的系统调用,加深对进程、线程等概念的理解;学习Linux对线程的独特的实现方式。
第一个实验
程序selective_wait.c
#include <stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
main()
{
int pid1, pid2, pid3, pid4;
pid1 = fork();
if (pid1 == 0) {
printf("first child\n");
sleep(10);
printf("first child terminates\n");
exit(0);
}
pid2 = fork();
if (pid2 == 0) {
printf("second child\n");
sleep(20);
printf("second child terminates\n");
exit(0);
}
pid3 = fork();
if (pid3 == 0) {
printf("third child\n");
sleep(30);
printf("third child terminates\n");
exit(0);
}
pid4 = fork();
if (pid4 == 0) {
printf("fourth child\n");
sleep(40);
printf("fourth child terminates\n");
exit(0);
}
waitpid(pid2, NULL, 0);
printf("parent: second child terminated\n");
}
第二个实验
实验代码
#include<unistd.h>
#include<stdlib.h>
#include <stdio.h>
#include <sched.h>
char stack[1024]; // used by the cloned process as stack space
int sharedVariable; // the shared variable
int clone_process(void *s)
{
while (1) {
sleep(2);
sharedVariable ++;
printf(“cloned process: %d \n”, sharedVariable);
}
}
main()
{
int rc;
rc = clone(clone_process, &stack[1024], CLONE_VM, 0);
if (rc < 0) {
printf(“main process: clone() failed \n”);
exit(1);
}
while (1) {
sleep(3);
sharedVariable--;
printf(“main process: %d \n”, sharedVariable);
}
}