How to close an application itself and a terminal?

14,582

Solution 1

The system command creates a new shell process and issues the command to that shell, so when you issue exit it will close only the new shell.

The way to do what you ask for is this:

#include <unistd.h>
#include <signal.h>
int main(int argc, char *argv[])
{
    kill(getppid(), SIGKILL);
    return 0;
}

However, this is A BAD IDEA (for many reasons: you are blindly killing some process that spawned yours with no real clue what it actually is... it could be the user's login shell, or it could be init). You probably just want to close the terminal window, right? Then launch your program like this:

xterm -e my_program

This will run your program in its own window, which closes when the program finishes. No trickery, and it works with any program.

Solution 2

Your "exit" command is not being sent to the shell that launched your program, but rather a new shell, executed expressly for the purpose of executing your command. It doesn't accomplish anything.

There's no way for your program to cleanly exit the shell that launched it without some cooperation from that shell. For example, assuming we're running with bash or Bourne shell on UNIX, if in the terminal, you start your program using

exec theprogname

then the launching shell is replaced by your program, and so when your program exits, the shell exits.

Solution 3

Maybe it will work if You use signal on terminating the program. a. k. a.

#include <signal.h>
#include <stdio.h>

void terminate(int param)
{
   system("exit");
}

int main()
{
   void (*sig)(int);
   sig = signal(SIGTERM, terminate);
   return 0;
}
Share:
14,582
9Ake
Author by

9Ake

Updated on June 05, 2022

Comments

  • 9Ake
    9Ake about 2 years

    In my C console application, I would like to exit the application and on the same time fire an exit command to close a terminal. However, following code seems not work. Once I run the application, it exit the application, but not close the terminal.

    int main(void)
    {
      system("exit");
      return 0;
    }
    

    Please give any advise.

  • Ernest Friedman-Hill
    Ernest Friedman-Hill almost 13 years
    Sorry, but this makes no sense at all.
  • Dietrich Epp
    Dietrich Epp almost 13 years
    @Joey: Try it. SIGTERM fails, SIGKILL succeeds. (And killing an unknown process isn't going to be nice in the first place. It's like arguing whether you should rob someone at knifepoint or gunpoint, and which of the two is nicer.)
  • 9Ake
    9Ake almost 13 years
    Thank you very much for all answers here. This is exactly what I am looking for.