【问题标题】:What's the best approach to execute two programs at the same time in C?在 C 中同时执行两个程序的最佳方法是什么?
【发布时间】:2020-09-25 22:58:50
【问题描述】:

我有两个在 unix 中运行的程序 A 和 B。两者具有相同的优先级。两者都需要同时执行。我的问题是,从执行 A 和 B 的第三个程序 (C) 运行它们会更好,还是应该在 A 中运行程序 A 并执行 B?

在任何情况下我应该使用什么方法 exec() 调用或者我应该使用 forks....?

【问题讨论】:

标签: c unix fork exec


【解决方案1】:

这取决于这两个程序是否需要交互。

如果 A 和 B 只需要在不知道对方的情况下同时运行,只需从第三个程序 C(可能是 bash 脚本)启动它们。

如果 A 和 B 需要相互了解,例如A 必须在某个时候等待 B 完成,使用 fork()、exec()、wait()。当其中一个需要使用 kill() 停止另一个时,同样适用。对于所有这些场景,他们必须知道其他进程的 PID,这是由 fork() 为 A 和 getppid() 为 B 提供的。

【讨论】:

  • fork() 和 exec() 不知道“windows”的概念,他们只知道进程。进程(一旦启动)是否在屏幕上显示矩形内容取决于它们。
【解决方案2】:

可以使用不同的方法。一个可能的解决方案是它自己的程序,它简单地使用 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

【讨论】:

    猜你喜欢
    • 2023-03-21
    • 1970-01-01
    • 2017-12-10
    • 2020-09-27
    • 2022-06-10
    • 2022-01-01
    • 1970-01-01
    • 2018-02-16
    • 2012-04-17
    相关资源
    最近更新 更多