Search code examples
cmultithreadingprocesspthreadsterminate

Terminating Main on Secondary Process Completion


I have a Main C program that creates two threads and each of those threads starts a process using a system() call. Is it possible to terminate the main program as soon as either of those processes created by the threads finish operating?

#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;
}

Solution

  • The system function returns as soon as the command it invoked finishes. So the simplest possible way to terminate the process would be to have either thread call exit.

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

    Alternatively you can call pthread_join in the main thread, but that way you have to wait for one specific thread to finish.