OS program in C under Unix

2010-02-28 1:22 am
小弟學緊Operating System & System Programming

我係C的的初哥,應該話完全唔識,以下的要求,應該點寫.... 用C language under Unix:

Write a program under Unix with the following characteristics.

A parent process creates two children processes.
The first child process will sleep 1 second.
The second child process will sleep 10 seconds.
The parent waits for the first child to complete, and kills the second child when thefirst one completes.
After that, the parent writes: “Process X has waited forProcess Y to complete and killed Process Z.”
(where X is the process id of the parent, and Y and Z are the process ids of these two children).
Finally, the parent exits.

Please also provide necessary comments.

回答 (1)

2010-03-09 1:51 am
✔ 最佳答案
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
pid_t pid1, pid2;

int p1_stat;

pid1 = fork();
if (pid1 < 0) {
perror("fork failed"); exit(1);
}

pid2 = fork();
if (pid2 < 0) {
perror("fork failed"); exit(1);
}

if (pid1 == 0) { // child 1
sleep(1);
printf("Done with process 1\n");
exit(0);
}

if (pid2 == 0) { // child 2
sleep(10);
printf("Done with process 2\n");
exit(0);
}

if (pid1 != 0 && pid2 !=0) { // Parent
waitpid(pid1, &p1_stat, 0);

if (WIFEXITED(p1_stat)) {
printf("Child exited with code %d\n", WEXITSTATUS(p1_stat));
if (kill(pid2,SIGKILL) == 0)
printf("Child process 2 killed\n");
}

}
return 0;
}

http://www28.discuss.com.hk/viewthread.php?tid=11639601


收錄日期: 2021-04-19 21:25:15
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20100227000051KK01139

檢視 Wayback Machine 備份