这是我的编程问题的修订版:
- 分叉两个运行随机时间的空闲进程,每个进程运行时间在 0 到 20 秒之间。
- 进程应使用信号 SIGSTOP 和 SIGCONT 将进程安排在循环队列中。
- 当子进程都为每个空闲进程终止时,父进程也应该终止。
- 如果其中一个子进程终止,它应该继续运行,直到它们都使用 SIGCHLD 终止。
这是关于我有多远。
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
using namespace std;
using std::cout;
volatile sig_atomic_t keep_going = 1;
void catch_child (int sig)
{ int status, p;
p = waitpid(-1,&status,WNOHANG);
if (p==0) return;
keep_going=0;
cout<<"Child process caught: "<< p <<endl;
return;
}
int main()
{
pid_t pid;
pid_t mypid;
int rand1;
rand1 = rand()%20;
signal (SIGCHLD, catch_child);
pid = fork();
if (pid<0) {
cout<<"Error\n";
return 0;
}
else if (pid==0) {
mypid = getpid();
cout << "Child pid is " << mypid << "\n";
execlp("./idle","./idle","1",rand1,0);
} else {
mypid=getpid();
cout<<"parent procss is "<<mypid<<" and child is "<<pid<<"\n";
sleep(5);
cout<<"pausing child "<<pid<<" for 5 seconds\n";
kill(pid,SIGSTOP);
for (int i=0; i<5; i++) sleep(1);
cout<<"Resuming child "<<pid<<"\n";
kill(pid,SIGCONT);
cout<<"Parent process pid is "<<mypid<<" waiting for child to stop\n";
while (keep_going==1) sleep(1);
// wait(NULL);
cout <<"Parent knows that Child now done\n";
}
return 0;
}