我有一个主 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/