#include<stdio.h> #include<stdlib.h> #include<signal.h> #include<unistd.h> void waiting(),stop(); int wait_mark; main(){ int p1,p2,stdout; while((p1=fork())== -1); if(p1> 0){ while((p2=fork())== -1); if(p2> 0){ wait_mark= 1; signal(SIGINT,stop); waiting(); kill(p1,16); kill(p2,17); wait(0); wait(0); printf("Parent process is killed!\n"); exit(0); } else{ wait_mark= 1; signal(17,stop); waiting(); lockf(stdout,1,0); printf("Child process 2 is killed by parent!\n"); lockf(stdout,0,0); exit(0);} } else{ wait_mark= 1; signal(16,stop); waiting(); lockf(stdout,1,0); printf("Child process 1 is killed by parent!\n"); lockf(stdout,0,0); exit(0);} } void waiting(){ while(wait_mark!= 0);} void stop(){ wait_mark= 0;}中lockf(stdout,1,0)的作用是什么? 2、该程序段前面部分用了两个wait(0),它们起什么作用? 3、该程序段中每个进程退出时都用了语句exit(0),为什么? 4、为何预期的结果并未显示出? 5、程序该如何修改才能得到正确结果?
时间: 2024-03-13 21:44:28 浏览: 18
1. lockf(stdout,1,0)的作用是对标准输出流进行加锁,防止多个进程同时写入导致混乱。
2. wait(0)的作用是等待子进程结束并回收其资源,其中0表示任何子进程结束都可以。
3. exit(0)的作用是正常退出进程,并返回0表示程序执行成功。在这个程序中,每个进程都是通过exit(0)来结束的。
4. 预期的结果应该是父进程先输出"Parent process is killed!",然后子进程2输出"Child process 2 is killed by parent!",最后子进程1输出"Child process 1 is killed by parent!"。但是实际运行结果可能与预期不符,这是因为输出的顺序是不确定的,取决于进程运行的顺序和系统调度的策略。
5. 可以通过在每个输出语句前加锁和刷新缓冲区,以保证输出顺序的正确性。修改后的代码如下:
```c
#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<unistd.h>
void waiting(),stop();
int wait_mark;
main(){
int p1,p2,stdout;
while((p1=fork())== -1);
if(p1> 0){
while((p2=fork())== -1);
if(p2> 0){
wait_mark= 1;
signal(SIGINT,stop);
waiting();
lockf(stdout,1,0);
printf("Parent process is killed!\n");
fflush(stdout);
lockf(stdout,0,0);
exit(0);
} else{
wait_mark= 1;
signal(17,stop);
waiting();
lockf(stdout,1,0);
printf("Child process 2 is killed by parent!\n");
fflush(stdout);
lockf(stdout,0,0);
exit(0);
}
} else{
wait_mark= 1;
signal(16,stop);
waiting();
lockf(stdout,1,0);
printf("Child process 1 is killed by parent!\n");
fflush(stdout);
lockf(stdout,0,0);
exit(0);
}
}
void waiting(){
while(wait_mark!= 0);
}
void stop(){
wait_mark= 0;
}
```