【发布时间】:2018-10-17 15:45:42
【问题描述】:
在下面的代码中,依靠 read() failure 来检测孩子的终止是否安全?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
int pipefd[2];
pipefd[0] = 0;
pipefd[1] = 0;
pipe(pipefd);
pid_t pid = fork();
if (pid == 0)
{
// child
close(pipefd[0]); // close unused read end
while ((dup2(pipefd[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {} // send stdout to the pipe
while ((dup2(pipefd[1], STDERR_FILENO) == -1) && (errno == EINTR)) {} // send stderr to the pipe
close(pipefd[1]); // close unused write end
char *argv[3];
argv[0] = "worker-app";
argv[1] = NULL;
argv[2] = NULL;
execvp("./worker-app", argv);
printf("failed to execvp, errno %d\n", errno);
exit(EXIT_FAILURE);
}
else if (pid == -1)
{
}
else
{
// parent
close(pipefd[1]); // close the write end of the pipe in the parent
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
while (1) // <= here is it safe to rely on read below to break from this loop ?
{
ssize_t count = read(pipefd[0], buffer, sizeof(buffer)-1);
printf("pipe read return %d\n", (int)count);
if (count > 0)
{
printf("child: %s\n", buffer);
}
else if (count == 0)
{
printf("end read child pipe\n", buffer);
break;
}
else if (count == -1)
{
if (errno == EINTR)
{ continue;
}
printf("error read child pipe\n", buffer);
break;
}
}
close(pipefd[0]); // close read end, prevent descriptor leak
int waitStatus = 0;
waitpid(pid, &waitStatus, 0);
}
fprintf(stdout, "All work completed :-)\n");
return EXIT_SUCCESS;
}
我应该在 while(1) 循环中添加一些东西来检测子终止吗?可能会发生什么特定情况并破坏此应用程序?
下面的一些改进想法。但是我会浪费 CPU 周期吗?
使用带有特殊参数 0 的 kill 不会终止进程,而只是检查它是否响应:
if (kill(pid, 0)) { break; /* child exited */ };/* 如果 sig 为 0,则不发送信号,但仍进行错误检查;这可用于检查进程 ID 或进程组 ID 是否存在。 https://linux.die.net/man/2/kill */在 while(1) 循环中使用 waitpid 非阻塞来检查子进程是否已退出。
使用 select() 检查管道可读性以防止 read() 可能挂起?
谢谢!
【问题讨论】: