2012-07-26 114 views
0

我有一個Main 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; 
} 

回答

1

system函數一旦它調用的命令完成就會返回。所以終止這個過程的最簡單的方法是讓線程調用exit

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

另外,您可以撥打pthread_join在主線程,但這種方式,你必須等待一個特定的線程來完成。