TLPI-Chapter 26 监控子进程

2018-02-05 10:31:25来源:http://www.52murong.com/post/TLPI-Chapter26作者:52coder人点击

分享
/*************************************************************************/
*Copyright (C) Michael Kerrisk, 2017. *
* *
* This program is free software. You may use, modify, and redistribute it *
* under the terms of the GNU General Public License as published by the *
* Free Software Foundation, either version 3 or (at your option) any*
* later version. This program is distributed without any warranty.See *
* the file COPYING.gpl-v3 for details.*
/*************************************************************************/
/* Listing 26-1 */
#include <sys/wait.h>
#include <time.h>
#include "curr_time.h"/* Declaration of currTime() */
#include "tlpi_hdr.h"
int
main(int argc, char *argv[])
{
int numDead; /* Number of children so far waited for */
pid_t childPid;/* PID of waited for child */
int j;
if (argc < 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s sleep-time.../n", argv[0]);
setbuf(stdout, NULL); /* Disable buffering of stdout */
for (j = 1; j < argc; j++) {/* Create one child for each argument */
switch (fork()) {
case -1:
errExit("fork");
case 0: /* Child sleeps for a while then exits */
printf("[%s] child %d started with PID %ld, sleeping %s "
"seconds/n", currTime("%T"), j, (long) getpid(),
argv[j]);
sleep(getInt(argv[j], GN_NONNEG, "sleep-time"));
_exit(EXIT_SUCCESS);
default:/* Parent just continues around loop */
break;
}
}
numDead = 0;
for (;;) {/* Parent waits for each child to exit */
childPid = wait(NULL);
if (childPid == -1) {
if (errno == ECHILD) {
printf("No more children - bye!/n");
exit(EXIT_SUCCESS);
} else {/* Some other (unexpected) error */
errExit("wait");
}
}
numDead++;
printf("[%s] wait() returned child PID %ld (numDead=%d)/n",
currTime("%T"), (long) childPid, numDead);
}
}

执行结果


root@ubuntu:~/tlpi-book/procexec# ./multi_wait 1 2 3 4 5


[15:14:31] child 1 started with PID 28487, sleeping 1 seconds


[15:14:31] child 2 started with PID 28488, sleeping 2 seconds


[15:14:31] child 3 started with PID 28489, sleeping 3 seconds


[15:14:31] child 4 started with PID 28490, sleeping 4 seconds


[15:14:31] child 5 started with PID 28491, sleeping 5 seconds


[15:14:32] wait() returned child PID 28487 (numDead=1)


[15:14:33] wait() returned child PID 28488 (numDead=2)


[15:14:34] wait() returned child PID 28489 (numDead=3)


[15:14:35] wait() returned child PID 28490 (numDead=4)


[15:14:36] wait() returned child PID 28491 (numDead=5)


No more children - bye!


该程序创建多个子进程,每个子进程对应于一个(整型)命令行参数。每个子进程休眠若干秒后退出,休眠时间分别由相应各命令行参数指定,在创建所有子进程之后,父进程循环调用wait()来监控这些子进程的终止。而直到wait()返回-1时才会退出循环。当调用进程并无之前未被等待的子进程,此时会将errno置为ECHILD。

最新文章

123

最新摄影

闪念基因

微信扫一扫

第七城市微信公众平台