How to exit program from a thread in C?

Viewed 501

How can a program be stopped from a non-main thread?

I'm creating a new thread.

/* Listen for user commands in new thread */
pthread_t tid;
pthread_create(&tid, NULL, &commands, NULL);

I want to stop the program if the user types exit.

/* Listen for user input */
void *commands(void *arg)
{
    char command[100]; 
    while(1)
    {
        printf("Type 'exit' to stop program\n");
        fgets (command, 100, stdin); 
        if(strcmp(command, "exit") == 0) {
            // TODO exit
        }
    }
}

I tried calling exit(0) from the commands method but this did nothing.

2 Answers

You should call pthread_exit to exit your thread correctly. Note that your application should wait for it to exit using pthread_join.

To answer my own question: Exiting the program from a new thread is possible via exit() function. In my code sample the if block which contains the exit() function was never accessed. The following code works fine:

/* Listen for user input */
void *commands(void *arg)
{
    char command[100]; 
    while(1)
    {
        printf("Type 'exit' to stop program\n");
        fgets (command, 100, stdin); 
        if(strcmp(command, "exit\n") == 0) {
            exit(0)
        }
    }
}

However, I'm not sure if just calling exit() stops other threads correctly.

Related