如果我理解正确,您想创建一个子进程,在该进程中运行一个程序,然后等待它完成。当直接使用系统原语时,这三个步骤中的每一个都是在 Unix 上的自己的操作。你已经知道fork() 和execlp();第三步,等待子进程完成,由waitpid() 及其亲属完成。
以 Basile 所写的内容为基础,以下是缺失的部分:
#define _POSIX_C_SOURCE 200809L /* strsignal */
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
void run_program(void)
{
int status;
pid_t pid;
fflush(0);
/* create the subprocess */
pid = fork();
if (p < 0) { /* fork failed */
perror("fork");
exit(1);
}
/* in the child only, execute a program */
if (p == 0) {
execlp(RUN_EXE, RUN_EXE, SPEC_RUN.run_args[j], (char *)0);
/* If execlp returns, it failed. It is unsafe to call `exit` if this
happens; you must instead use `_exit`. This means you have to flush
output manually. */
fprintf(stderr, "execlp: %s: %s\n", RUN_EXE, strerror(errno));
fflush(stderr);
_exit(1);
}
/* in the parent, wait for the child to finish */
if (waitpid(pid, &status, 0) != pid) {
perror("waitpid");
exit(1);
}
/* decode and report any failure of the child */
if (WIFEXITED(status)) {
if (WEXITSTATUS(status) == 0)
return; /* success! */
fprintf(stderr, "%s: unsuccessful exit %d\n",
RUN_EXE, WEXITSTATUS(status));
exit(1);
}
if (WIFSIGNALED(status)) {
fprintf(stderr, "%s: %s%s\n",
RUN_EXE,
strsignal(WTERMSIG(status)),
WCOREDUMP(status) ? " (core dumped)" : "");
exit(1);
}
fprintf(stderr, "%s: impossible exit status %04x\n",
RUN_EXE, status);
exit(1);
}
...如果这看起来像一个你不想处理的巨大的头发球,你应该考虑使用更高级别的库函数system() 和/或popen()。它们有自己的缺陷——最重要的是,它们通过/bin/sh,这通常不是你想要的——但在简单的情况下它们更容易使用。