本实验报告深入探讨了操作系统中的进程管理机制,通过理论与实践结合的方式,详细分析了进程创建、调度及同步等关键操作,并提出优化建议。
进程的软中断通信可以通过信号处理来实现。下面是一个示例代码:
```c
#include
#include
#include
#include
int wait_flag;
void stop() {
wait_flag = 0;
}
int main( ) {
int pid1, pid2; // 定义两个进程号变量
signal(SIGINT,stop); // 或者可以使用信号SIGTERM来处理终止请求
while((pid1 = fork()) == -1);
if(pid1 > 0) {
// 子进程创建成功,pid1为父进程的子进程标识符
while((pid2 = fork( )) == -1);
if(pid2 > 0) {
wait_flag = 1;
kill(pid1, SIGUSR1); // 发送信号给第一个子进程以终止它
kill(pid2, SIGUSR2); // 同样发送第二个子进程的终止信号
wait(0);
wait(0);
printf(\nParent process is killed !!\n);
exit(0);
} else {
wait_flag = 1;
signal(SIGUSR2, stop);
printf(\nChild process 2 is killed by parent !!\n);
exit(0);
}
} else {
wait_flag = 1;
signal(SIGUSR1,stop);
printf(\nChild process 1 is killed by parent !!\n);
exit(0);
}
}
```
进程的管道通信可以通过创建一个共享内存区域(即管道)来实现,下面是一个示例代码:
```c
#include
#include
#include
int pid1, pid2; // 定义两个进程变量
int main( ) {
int fd[2];
char OutPipe[100], InPipe[100];
pipe(fd);
while((pid1 = fork()) == -1);
if(pid1 == 0) {
lockf(fd[1], 1, 0);
sprintf(OutPipe,\nChild process 1 is sending message!\n);
write(fd[1], OutPipe, sizeof(OutPipe));
sleep(5);
lockf(fd[1], 0, 0);
exit(0);
} else {
while((pid2 = fork()) == -1);
if(pid2 == 0) {
lockf(fd[1], 1, 0);
sprintf(OutPipe,\nChild process 2 is sending message!\n);
write(fd[1], OutPipe, sizeof(OutPipe));
sleep(5);
lockf(fd[1], 0, 0);
exit(0);
} else {
wait(NULL);
read(fd[0], InPipe, sizeof(InPipe));
printf(%s\n,InPipe);
wait(NULL);
read(fd[0], InPipe, sizeof(InPipe));
printf(%s\n,InPipe);
exit(0);
}
}
}
```
这两个示例分别展示了如何通过信号和管道实现进程间的通信。