下載/瀏覽Download

Download Report

Transcript 下載/瀏覽Download

建立子行程(1/2)
EOS STUT
1
建立子行程(2/2)
EOS STUT
2
C Program Forking Separate Process
int main()
{
Pid_t pid;
/* fork another process */
pid = fork();
if (pid < 0) { /* error occurred */
fprintf(stderr, "Fork Failed");
exit(-1);
}
else if (pid == 0) { /* child process */
execlp("/bin/ls", "ls", NULL);
}
else { /* parent process */
/* parent will wait for the child to complete */
wait (NULL);
printf ("Child Complete");
exit(0);
}
}
EOS STUT
3
Termination of process
 5 ways to terminate a process

Normal termination




The return in main() (== exit(main(argv, argv)); )
Call exit , defined by ANSI C
Call _exit, defined by POSIX.1
Abnormal termination


Call abort, the function issues SIGABRT signal
Terminated by signal , these signals are issued by other processes (call abort for example)
 The kernel closes opened file descriptor, release the process’s
memory, and etc.
 The exit status shall pass to the parent
If parent terminates earlier, all children will set their parent to 1, i.e. init
If child terminates earlier than parent, kernel stores the exit status,
waiting for parent’s reading (call wait or waitpid)
 If there are no wait or relatives, i.e. no reading of child status, the child
becomes zombie


 When a process terminates, kernel will send a SIGCHLD signal to its
parent
EOS STUT
4
Waiting for process termination(1/3)
EOS STUT
5
Waiting for process termination(2/3)
EOS STUT
6
Waiting for process termination(3/3)
EOS STUT
7
A tree of processes on a typical Solaris
EOS STUT
8
Get process ID
EOS STUT
9
Show PID number
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main()
{
pid_t self, child;
self = getpid();
child = fork();
Parent process, PID: 5916
This is the child process. PID:5917
Child process ID:5917
if (child != 0) {
printf("Parent process, PID: %d\n", (int) self);
printf("Child process ID: %d\n", (int) child);
} else {
printf("This is the child process. PID: %d\n", (int) getpid());
}
}
return 0;
EOS STUT
10