Linux操作系统一个C程序错误

2025-01-02 23:14:07
推荐回答(2个)
回答1:

改waiting函数。修改后全部代码:
#include
#include
#include
void waiting();
void stop();
int wait_mark = 0;
int main()
{
int p1 = 0;
int p2 = 0;
while((p1 = fork()) == -1);
if(p1 > 0){
while((p2 = fork()) == -1);
if(p2 > 0){
printf("parent\n");
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{
printf("p2\n");
wait_mark = 1;
signal(17,stop);
waiting();
lockf(stdout,1,0);
printf("chile process 2 is killed by parent!\n");
lockf(stdout,0,0);
exit(0);
}
}
else{
printf("p1\n");
wait_mark = 1;
signal(16,stop);
waiting();
lockf(stdout,1,0);
printf("chile process 1 is killed by parent!\n");
lockf(stdout,0,0);
exit(0);
}
return 0;
}

void waiting()
{
while(wait_mark != 0)
{
signal(SIGINT,stop);
sleep(1);
}
}

void stop()
{
wait_mark = 0;
}

控制台执行可执行文件,看到:
new@linux-14y9:~> /home/new/Projects/CTest/lockf-build-desktop/lockf
p1
parent
p2

这时候按下Ctrl+C,现在要Ctrl+C才能触发SIGINT信号了。
按了Ctrl+C后,看到结果:
new@linux-14y9:~> /home/new/Projects/CTest/lockf-build-desktop/lockf
p1
parent
p2
^Cchile process 1 is killed by parent!
chile process 2 is killed by parent!
parent process is killed!

清华不少书都是坑爹,计算机还是学外文翻译来的教材好。

回答2:

编译没通过吧?
#include