+ -
当前位置:首页 → 问答吧 → 老师的作业,谁帮帮我呀!!

老师的作业,谁帮帮我呀!!

时间:2004-11-03

来源:互联网

Exercises:
1. Please write a C program that does the following things:
a. It shows it own pid and ppid on the screen.
b. It creates a child process. The parent process shows then the pid of this child process, it sleeps for one second and outputs a message on the screen saying that it will exit.
c. The child process shows its pid and ppid on the screen. It sleeps for 5 seconds and outputs its pid and ppid again on the screen before it exits.
d. Redirect the outputs of the program to a temp file and compare the contents of this file with those directly shown on the screen. You will find that they are different! But both are correct! Could you explain the reason for the differences?
Question: How have you made the child process an orphan? Have the two ppids shown by the child process the same value? If true, why are they identical? If not true, what value is the ppid of the child process after the parent process has exited?
Hints: To get the pid and ppid of a process, the following two functions may be used:
pid_t getpid(void);
pid_t getppid(void);

作者: ptman   发布时间: 2004-11-03

代码:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>


int main(int argc, char *argv[])
{
 pid_t pid;
 FILE fp;
 
 printf("1 My own pid = %d\n My ppid = %d\n",
 getpid(),getppid());
 if( (pid = fork()) < 0) {
 printf("Error!!!\n");
 exit(0);
 } if (pid == 0) {
 printf("2 MY child process id = %d\n MY parent procss id = %d\n", 
 getpid(), getppid());
 sleep (5);
 printf("after 5s\n");
 printf("2 MY child process id = %d\n MY parent procss id = %d\n", 
 getpid(), getppid());
 } else {
 printf("3 The child process id is(I am parent) = %d\n", pid);
 sleep(1);
 printf("3 I will go, if u miss me ,just call me:)\n");
 }

 return 0;
}

作者: toorq   发布时间: 2004-11-03