您应该始终尝试将问题拆分为较小的子问题,以便您首先解决和验证。
例如,考虑是否为您提供了以下 run.h:
#ifndef RUN_H
#define RUN_H
#include <sys/types.h>
/** Create a close-on-exec pipe with descriptors not standard streams
*
* Both read and write end of the pipe will be close-on-exec,
* and neither of them will be 0 (stdin), 1 (stdout), or 2 (stderr).
*
* @fd Read ([0]) and write ([1]) ends of the pipe
* @return 0 if success, -1 with errno set if error
*/
int safe_pipe(int fd[2]);
/* pgid: */
enum {
NEW_SESSION = -2,
NO_CHANGE = -1,
NEW_PGROUP = 0,
};
/* Descriptors: */
enum {
DEV_NULL = -1,
STANDARD_INPUT = 0,
STANDARD_OUTPUT = 1,
STANDARD_ERROR = 2,
};
/** Execute a binary in a child process
*
* This function uses a control pipe to check if the specified binary could be executed
* (started; not completed!), and to provide the errno number if not.
* It is careful to ensure even oddball descriptor configurations work.
* It is up to the parent to close any pipe descriptors specified after the call.
*
* @pathname Name or path to the binary to be executed.
* @args NULL-terminated array of command-line arguments.
* Note that args[0] is the command name itself.
* @pgid Process group to use: NEW_SESSION, NO_CHANGE, NEW_PGROUP,
* or a process group ID. NO_CHANGE runs the child process
* in the same session and process group as the current process.
* @infd Standard input descriptor. DEV_NULL, 0, or a pipe descriptor.
* @outfd Standard output descriptor. DEV_NULL, 1, or a pipe descriptor.
* @errfd Standard error descriptor. DEV_NULL, 2, or a pipe descriptor.
* @return PID of the child process, or -1 with errno set if an error occurs.
*/
pid_t run(const char *pathname, const char *args[], pid_t pgid, int infd, int outfd, int errfd);
/** Wait for all child processes to finish, and reap them
*
* errno is always set when this function returns:
* ECHILD if there are no more child processes
* EINTR if wait was interrupted by signal delivery
* or any other positive value returned by reaped().
*
* @reaped NULL, or a function called for each reaped child process.
* First parameter is the PID of the child process that exited,
* the second parameter is the "packed" exit status code; see man 2 wait.
* If reaped() returns a negative value, wait_all_children() will
* immediately return with that value, keeping the same errno value.
* If reaped() returns a positive value, wait_all_children() will
* immediately return with the reaped process count, and that value in errno.
* @return Number of processes reaped, or negative if an error occurs.
*/
int wait_all_children(int (*reaped)(pid_t, int));
#endif /* RUN_H */
及其知识共享零许可(随意使用!)实现,run.c:
// SPDX-License-Identifier: CC0-1.0
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include "run.h"
/* Create a close-on-exec pipe whose read and write ends do not
* overlap with standard descriptors (stdin, stdout, stderr).
* Returns 0 if success, -1 with errno set if error.
*/
int safe_pipe(int fd[2])
{
unsigned int close_mask = 0;
int err = 0;
int pfd[2];
fd[0] = -1;
fd[1] = -1;
if (pipe2(pfd, O_CLOEXEC) == -1) {
/* errno set by pipe2() */
return -1;
}
do {
/* Make sure read end does not shadow standard descriptors */
while (pfd[0] >= 0 && pfd[0] <= 2) {
close_mask |= 1 << pfd[0];
pfd[0] = fcntl(pfd[0], F_DUPFD_CLOEXEC, 3);
if (pfd[0] == -1) {
err = errno;
break;
}
}
if (err)
break;
/* Make sure write end does not shadow standard descriptors */
while (pfd[1] >= 0 && pfd[1] <= 2) {
close_mask |= 1 << pfd[1];
pfd[1] = fcntl(pfd[1], F_DUPFD_CLOEXEC, 3);
if (pfd[1] == -1) {
err = errno;
break;
}
}
if (err)
break;
/* Close any temporarily used descriptors. */
if (close_mask & (1<<0))
close(0);
if (close_mask & (1<<1))
close(1);
if (close_mask & (1<<2))
close(2);
/* Success! */
fd[0] = pfd[0];
fd[1] = pfd[1];
return 0;
} while (0);
/* Failed. Close all related descriptors. */
if (pfd[0] != -1)
close(pfd[0]);
if (pfd[1] != -1)
close(pfd[1]);
if (close_mask & (1<<0))
close(0);
if (close_mask & (1<<1))
close(1);
if (close_mask & (1<<2))
close(2);
errno = err;
return -1;
}
/* Open the null device to a specific descriptor.
*/
static int dev_null(int to_descriptor)
{
int fd;
if (to_descriptor == -1) {
errno = EBADF;
return -1;
}
close(to_descriptor);
fd = open("/dev/null", O_RDWR | O_NOCTTY);
if (fd == -1)
return -1; /* errno set by open() */
if (fd == to_descriptor)
return 0; /* We got lucky! */
if (dup2(fd, to_descriptor) == -1) {
const int saved_errno = errno;
close(fd);
errno = saved_errno;
return -1;
}
close(fd);
return 0;
}
/* Execute a binary with the specified command-line arguments
* (args[] array terminated by a NULL pointer),
* and redirecting standard input, output, and error to the specified descriptors
* (which may, and should be, close-on-exec), or -1 to redirect to /dev/null.
* pgid can be -2 for a new session, -1 for no change, 0 for new process group, or >0 for a specific process group.
* Returns the PID of the new child process, or -1 with errno set if error.
*/
pid_t run(const char *pathname, const char *args[], pid_t pgid, int infd, int outfd, int errfd)
{
if (!pathname || !*pathname || !args || !args[0] || !args[0][0]) {
/* NULL or empty pathname (path or name) to the executable. */
errno = EINVAL;
return -1;
}
/* Create the control pipe we use between parent and child to monitor exec() success/failure. */
int ctrlfd[2];
if (safe_pipe(ctrlfd) == -1) {
/* errno set by safe_pipe(). */
return -1;
}
pid_t child = fork();
if (child == -1) {
/* Cannot fork a child process. */
const int saved_errno = errno;
close(ctrlfd[0]);
close(ctrlfd[1]);
errno = saved_errno;
return -1;
} else
if (!child) {
/* Child process. */
unsigned int close_mask = 0;
int err = 0;
do {
/* Close parent (read) end of the control pipe. */
close(ctrlfd[0]);
/* Adjust process group. */
if (pgid == NEW_SESSION) {
if (setsid() == -1) {
err = errno;
break;
}
} else
if (pgid == NEW_PGROUP) {
if (setpgid(0, 0) == -1) {
err = errno;
break;
}
} else
if (pgid > 0) {
if (setpgid(0, pgid) == -1) {
err = errno;
break;
}
} else
if (pgid != NO_CHANGE) {
err = EINVAL;
break;
}
/* Make sure infd does not shadow standard output or standard error. */
while (infd == 1 || infd == 2) {
close_mask |= 1 << infd;
infd = fcntl(infd, F_DUPFD_CLOEXEC, 3);
if (infd == -1) {
err = errno;
break;
}
}
if (err)
break;
/* Make sure outfd does not shadow standard input or standard error. */
while (outfd == 0 || outfd == 2) {
close_mask |= 1 << outfd;
outfd = fcntl(outfd, F_DUPFD_CLOEXEC, 3);
if (outfd == -1) {
err = errno;
break;
}
}
if (err)
break;
/* Make sure errfd does not shadow standard input or standard output. */
while (errfd == 0 || errfd == 1) {
close_mask |= 1 << errfd;
errfd = fcntl(errfd, F_DUPFD_CLOEXEC, 3);
if (errfd == -1) {
err = errno;
break;
}
}
if (err)
break;
/* Close unneeded descriptors. */
if ((close_mask & (1<<0)) || infd == -1)
close(0);
if ((close_mask & (1<<1)) || outfd == -1)
close(1);
if ((close_mask & (1<<2)) || errfd == -1)
close(2);
/* Redirect standard input. */
if (infd == DEV_NULL) {
if (dev_null(0) == -1) {
err = errno;
break;
}
infd = 0;
} else
if (infd != 0) {
if (dup2(infd, 0) == -1) {
err = errno;
break;
}
close(infd);
infd = 0;
}
/* Redirect standard output. */
if (outfd == DEV_NULL) {
if (dev_null(1) == -1) {
err = errno;
break;
}
outfd = 1;
} else
if (outfd != 1) {
if (dup2(outfd, 1) == -1) {
err = errno;
break;
}
close(outfd);
outfd = 1;
}
/* Redirect standard error. */
if (errfd == DEV_NULL) {
if (dev_null(2) == -1) {
err = errno;
break;
}
errfd = 2;
} else
if (errfd != 2) {
if (dup2(errfd, 2) == -1) {
err = errno;
break;
}
close(errfd);
errfd = 2;
}
/* Make sure the standard descriptors are not close-on-exec. */
if (fcntl(0, F_SETFD, 0) == -1 ||
fcntl(1, F_SETFD, 0) == -1 ||
fcntl(2, F_SETFD, 0) == -1) {
err = errno;
break;
}
/* Close the unneeded temporary descriptors. */
if (close_mask & (1<<0))
close(0);
if (close_mask & (1<<1))
close(1);
if (close_mask & (1<<2))
close(2);
close_mask = 0;
/* Execute. */
if (strchr(pathname, '/'))
execv(pathname, (char *const *)args); /* pathname has a slash, so it is a path to a binary */
else
execvp(pathname, (char *const *)args); /* pathname has no slash, so it specifies the binary name only */
/* Failed. */
err = errno;
} while (0);
/* Send err to parent via the control pipe. */
{
const char *ptr = (const char *)(&err);
const char *const end = (const char *)(&err) + sizeof err;
while (ptr < end) {
ssize_t n = write(ctrlfd[1], ptr, (size_t)(end - ptr));
if (n > 0) {
ptr += n;
} else
if (n != -1) {
/* Should never occur */
break;
} else
if (errno != EINTR) {
/* I/O error writing to the pipe too! */
break;
}
}
}
/* The kernel will close all open descriptors in the process. */
exit(127);
}
/* Parent process. */
/* Close read end of control pipe, so we detect if the child process exec() succeeded. */
close(ctrlfd[1]);
/* Read from the control pipe, to determine if child process exec succeeds or not. */
{
int err = 0;
char *ptr = (char *)(&err);
char *const end = (char *)(&err) + sizeof err;
while (ptr < end) {
ssize_t n = read(ctrlfd[0], ptr, (size_t)(end - ptr));
if (n > 0) {
ptr += n;
} else
if (n == 0) {
break;
} else
if (n != -1) {
err = EIO;
ptr = end;
break;
} else
if (errno != EINTR) {
err = errno;
ptr = end;
break;
}
}
close(ctrlfd[0]);
/* Treat partially received errors and received zero as EIO. */
if (ptr > (char *)(&err)) {
if (ptr != end || !err)
err = EIO;
}
if (err) {
/* Child failed to exec; reap it. */
/* Reap child process. Ignore errors, and retry if interrupted. */
pid_t p;
do {
p = waitpid(child, NULL, 0);
} while (p == -1 && errno == EINTR);
errno = err;
return -1;
}
}
/* Success. */
errno = 0;
return child;
}
int wait_all_children(int (*reaped)(pid_t, int))
{
int count = 0;
while (1) {
int status = 0;
pid_t pid;
pid = wait(&status);
if (pid == -1) {
/* errno set by wait() */
return count;
} else
if (pid < 1) {
/* C library or Linux kernel bug! */
errno = EIO;
return count;
}
count++;
if (reaped) {
int retval = reaped(pid, status);
if (retval < 0) {
/* errno set by reaped() */
return retval;
} else
if (retval > 0) {
errno = retval;
return count;
}
}
}
}
和一个 Makefile 从 example.c 构建示例程序:
CC := gcc
CFLAGS := -Wall -Wextra -O2
LDFLAGS :=
TARGETS := example
.PHONY: all clean
all: $(TARGETS)
clean:
rm -f $(TARGETS) *.o
%.o: %.c
$(CC) $(CFLAGS) -c $^
example: example.o run.o
$(CC) $(CFLAGS) $^ $(LDFLAGS) -o $@
请注意,本论坛将Tabs 转换为空格,并且Makefile 缩进必须使用Tabs 而不是空格。幸运的是,运行 sed -e 's|^ *|\t|' -i Makefile 通过将初始空格转换为制表符来修复上述问题以及大多数其他 Makefile。
上面的想法是为了帮助你走上正确的道路:
-
safe_pipe() 创建一个管道,当您执行任何 exec() 调用时,两端都会自动关闭。即使您关闭了一些标准描述符(标准输入、输出或错误),它也可以确保管道末端不会干扰标准描述符。
-
wait_all_children() 等待当前进程的所有直接子进程(即,该进程已分叉的子进程),直到没有更多子进程,等待被信号传递或可选报告功能(它认为一个参数)返回非零。
-
run() 派生一个子进程,根据需要重定向标准描述符,甚至处理进程组。它使用控制管道来检测 exec() 错误,并且不等待子进程退出,只等待子进程启动。
进程组很有用,因为如果每个逻辑任务都在自己的进程组中,您可以使用否定的进程组 ID 向特定组中的每个进程发送信号(如 KILL 或 TERM)。这确保了对于复杂的任务,当整个任务需要被杀死时,无论它已经分叉了多少个进程,你都可以很好地清理它。不过,对于简单的命令,我们不必担心进程组。
在我们做一个简单的示例程序之后最好检查一下上面的内容,比如说一个运行ls -laF | tr a-z A-Z | cat的程序,它列出了当前目录中的所有文件,但是将小写a到z转换为大写,使用三个子进程:
// SPDX-License-Identifier: CC0-1.0
#define _POSIX_C_SOURCE 200809L
#define _GNU_SOURCE
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include "run.h"
int report(pid_t pid, int code)
{
if (WIFEXITED(code)) {
if (WEXITSTATUS(code))
printf("Process %d exited with status %d.\n", (int)pid, WEXITSTATUS(code));
else
printf("Process %d exited with success (status 0).\n", (int)pid);
} else
if (WIFSIGNALED(code)) {
printf("Process %d died from signal %d.\n", (int)pid, WTERMSIG(code));
} else {
printf("Process %d died from unknown causes.\n", (int)pid);
}
return 0;
}
int main(void)
{
const char *cmd_a[] = { "ls", "-laF", NULL };
const char *cmd_b[] = { "tr", "a-z", "A-Z", NULL };
const char *cmd_c[] = { "cat", NULL };
int a_to_b[2], b_to_c[2];
pid_t a, b, c;
if (safe_pipe(a_to_b) == -1 || safe_pipe(b_to_c) == -1) {
fprintf(stderr, "Cannot create pipes: %s.\n", strerror(errno));
return EXIT_FAILURE;
}
c = run(cmd_c[0], cmd_c, NO_CHANGE, b_to_c[0], STANDARD_OUTPUT, STANDARD_ERROR);
if (c == -1) {
fprintf(stderr, "%s: %s.\n", cmd_c[0], strerror(errno));
return EXIT_FAILURE;
}
b = run(cmd_b[0], cmd_b, NO_CHANGE, a_to_b[0], b_to_c[1], STANDARD_ERROR);
if (b == -1) {
fprintf(stderr, "%s: %s.\n", cmd_b[0], strerror(errno));
kill(c, SIGKILL);
wait_all_children(NULL);
return EXIT_FAILURE;
}
a = run(cmd_a[0], cmd_a, NO_CHANGE, DEV_NULL, a_to_b[1], STANDARD_ERROR);
if (a == -1) {
fprintf(stderr, "%s: %s.\n", cmd_a[0], strerror(errno));
kill(b, SIGKILL);
kill(c, SIGKILL);
wait_all_children(NULL);
return EXIT_FAILURE;
}
close(a_to_b[0]);
close(a_to_b[1]);
close(b_to_c[0]);
close(b_to_c[1]);
wait_all_children(report);
return EXIT_SUCCESS;
}
report() 函数只报告哪个子进程已经退出以及如何退出。您可以省略它,使用wait_all_children(NULL); 而不是wait_all_children(report);,但报告功能对于调试和检查您在不同情况下可以观察到的退出状态非常有用。
我们必须管道:a_to_b 和 b_to_c。对的第一个描述符(a_to_b[0] 和 b_to_c[0])始终是读取端,第二个(a_to_b[1] 和 b_to_c[1])是写入端。我们的三个子进程是a、b和c,所以我们希望a的标准输出是a_to_b[1],b的标准输入是a_to_b[0],b的标准输出为b_to_c[1],c 的标准输入为b_to_c[1]。
我们需要先创建管道。
然后,我们需要运行(fork 和 exec)子进程。因为子进程会阻塞直到他们获得输入(或者他们看到输入结束),所以我们在管道中从最后一个到第一个创建子进程:首先是“消费者”,然后是“生产者”。这样,如果我们在整个链都正常之前失败了,生产者应该仍然在等待输入。
如果我们未能创建某些子进程,我们确实需要杀死已经启动的进程,并最好等待它们退出(通常称为,reap them)。
当子进程启动后,父进程需要关闭它的管道描述符副本,这样当“生产者”(管道列表中的第一个进程)退出并关闭管道的写端时,读取结束报告输入结束。
如果父进程没有关闭它的管道(写结束)描述符副本,“消费者”(从管道读取的子进程)将永远不会检测到输入结束——因为理论上,parent 进程仍然可以写入管道! – 一切似乎都“挂起”。
此时,管道中的进程开始工作。此时父进程可以做其他事情。 (一个有趣的场景是希望使用 filters:一系列进程,通常是一个脚本,将数据从一种格式转换为另一种格式。过滤器输出管道的读取端很有可能(或管道链)和输入管道的写端可以访问到父级,这样父级在写端写入要转换的数据,从读端读取转换后的数据。有点棘手,因为我们不能假设我们可以在读取任何内容之前写入所有内容,因此通常使用带有select() 或poll() 的非阻塞 I/O。本身没有任何硬,只需要正确完成即可。)
由于父进程除了等待管道进程完成其工作外无事可做,因此父进程只是等待它们退出。
由于Makefile,只需要运行make all && ./example即可编译运行示例程序。
因为整个问题被拆分为子问题(以一种对标准流造成最少问题的方式创建管道,并且不会意外泄漏到错误的子进程;并分叉并启动子进程以重定向其标准流,以健壮和可靠的方式),示例程序很短,并且在概念级别上易于理解。
在玩过那个例子之后,是时候探索和解释 run.c 是如何实现这些功能的,以及为什么做出这样的选择,但我已经被否决了因未回答所述问题而获得负分,因此我将在此停止。尽管如此,我仍然相信以这种方式逐步解决问题,在经过测试和理解的部分之上构建解决方案,而不是试图“修复”OP的当前代码,是正确的“答案”。 (话又说回来,这正是我只以访客身份发帖,从不注册的原因。)