c - 辅助进程完成时终止 Main

标签 c multithreading process pthreads terminate

我有一个主 C 程序,它创建两个线程,每个线程使用 system() 调用启动一个进程。是否可以在线程创建的进程完成操作后立即终止主程序?

#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <sys/shm.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>

extern errno;
key_t key = 1;
int *shm;

void* Start_Ether(){
    printf("Creating Ethernet Process\n");
    int ret = system("sudo ./Ether");
    if (ret < 0){
        printf("Error Starting Ethernet Process\n");
    }
}

void* Start_Display(){
    printf("Creating Display Process\n");
    int ret = system("./Display");
    if (ret < 0){
        printf("Error Starting Display Process\n");
    }
}

int main (int argc, char **argv)
{                       
    pthread_t Ether, opengl;
    int ret1, ret2;
    printf("**********************************************\nMain Started\n**********************************************\n");   
    ret2 = pthread_create(&opengl, NULL, &Start_Display, NULL);
    if (ret2 != 0){
       printf("Error in Creating Display Thread\n");
    }
    ret1 = pthread_create(&Ether, NULL, &Start_Ether, NULL);
    if (ret1 != 0){
        printf("Error in Creating Ether Thread\n");
    }
    while(1){
        continue;   
    }
    return 1;
}

最佳答案

system 函数在它调用的命令完成后立即返回。因此,终止进程的最简单方法是让任一线程调用 exit

void* Start_Display()
{
    /* ... */
    exit(0);
    return NULL;
}

或者,您可以在主线程中调用 pthread_join,但这样您就必须等待一个特定线程完成。

关于c - 辅助进程完成时终止 Main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11667821/

相关文章:

c - 无法解密函数参数 : pointer and pointer to pointer

c - 限制关键字 - 优化和别名影响

c - 使用 libdbus-1 实现 Get 和 GetAll

c - 如何创建函数,在 C 中没有 typedef 的情况下返回指向另一个函数的指针?

java - ExecutorService 不起作用,但单独创建线程可以

java - 等待线程不恢复

c++ - 我使用 Qt 的多线程应用程序出了什么问题(错误 SIGSEGV)

java - 对正在运行的进程执行命令

java - Process.waitFor() 一个线程

c# - 在什么情况下后台进程通常会自行终止?