可以使用不同的方法。一个可能的解决方案是它自己的程序,它简单地使用 fork/execlp/waitpid 执行程序 a 和程序 b。
它可能看起来像这样:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
int main() {
pid_t pid1 = fork();
if (pid1 == 0) { //child 1 = a
execlp("./a", "./a", NULL);
fprintf(stderr, "execution of a failed\n");
exit(EXIT_FAILURE);
} else if (pid1 > 0) { //parent
pid_t pid2 = fork();
if (pid2 == 0) { //child 2 = b
execlp("./b", "./b", NULL);
fprintf(stderr, "execution of b failed\n");
} else if (pid2 > 0) { //parent
int status1;
if(waitpid(pid1, &status1, 0) == -1) {
perror("waitpid for a failed");
exit(EXIT_FAILURE);
}
int status2;
if(waitpid(pid2, &status2, 0) == -1) {
perror("waitpid for b failed");
exit(EXIT_FAILURE);
}
if(WIFEXITED(status1)) {
printf("status of a=%d\n", WEXITSTATUS(status1));
}
if(WIFEXITED(status2)) {
printf("status of b=%d\n", WEXITSTATUS(status1));
}
return EXIT_SUCCESS;
} else {
perror("second fork failed");
return EXIT_FAILURE;
}
} else {
perror("first fork failed");
return EXIT_FAILURE;
}
}
要调用的测试程序(a 和 b)可以是:
#include <stdio.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
if(argc > 0) {
printf("%s executing...\n", argv[0]);
}
sleep(3);
if(argc > 0) {
printf("%s about to finish\n", argv[0]);
}
return 0;
}
调用测试程序会产生以下输出:
./b executing...
./a executing...
./a about to finish
./b about to finish
status of a=0
status of b=0