在C中同时执行两个程序的最佳方法是什么?

问题描述 投票:0回答:2

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

无论如何,我应该使用exec()调用什么方法,还是应该使用forks ....?

c unix fork exec
2个回答
1
投票

可以使用不同的方法。可能的解决方案是使用自己的程序,该程序仅使用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

1
投票

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.