-2

Is there any possibility to execute code even after the program exits the main() method?

Erick Robertson
  • 32,125
  • 13
  • 69
  • 98
Prabhu
  • 723
  • 2
  • 10
  • 29

9 Answers9

6

In C and C++, functions registered through atexit() can be called after main() returns.

In C++, static destructors can also be called after main() returns.

Community
  • 1
  • 1
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • I voted you up, as I meant to post the same. But to be technical, aren't registered atexit calls executed before main returns - right before, that is? – gnometorule Dec 21 '11 at 13:51
  • 1
    @gnometorule, how would the program know that `main()` *is about to return*? It makes more sense to wait for it to return, then act accordingly (since the runtime code is the one calling `main()` in the first place). – Frédéric Hamidi Dec 21 '11 at 13:56
  • Thanks for clarifying. It was an actual question. I visualized the exit sys call to call registered atexit functions, if any, in which case the exit call proper would return after them. – gnometorule Dec 21 '11 at 13:58
  • Ah, that's not the same thing. If `exit()` is called, `main()` never returns (since `exit()` itself does not return). I was thinking of the other case, returning from `main()` without calling `exit()`. – Frédéric Hamidi Dec 21 '11 at 14:01
  • +1 for the static dtors. Similarly, static ctors run before main is called.. – Martin James Dec 21 '11 at 15:18
2

Maybe some other thread can continue working after program exits main(), so I can say Yes!

public class Main extends Thread {

    public static void main(String[] args) {

        Thread thread = new Thread(new Main());
        thread.start();
        System.out.println("main is exiting");
    }

    @Override
    public void run() {
        try {
            sleep(1000);
            System.out.println("thread is running");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}
narek.gevorgyan
  • 4,165
  • 5
  • 32
  • 52
1

Yes for C#: Finalizers of objects that go out of scope only after main() has exited will be executed afterwards.

This does come in handy sometimes, e.g. to remove lockfiles

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
1

C++: sure. Just put it into the destructor of a global object, and it will be run after main returns (but keep in mind that there's no guarantee that any global object is still constructed).

(... although, the trick is that the "real" entrypoint of the executable usually is not your main, but another function that initializes globals, calls your main and when it returns it destroys them before terminating)

Matteo Italia
  • 123,740
  • 17
  • 206
  • 299
1

The only possibility you have is fork(), and exit() in the parent. There is no other way around that. Threads won't help.

fge
  • 119,121
  • 33
  • 254
  • 329
1

In C and C++, there's atexit(), which will call a function during "normal" termination.

chrisaycock
  • 36,470
  • 14
  • 88
  • 125
0

The simple answer is no. But you can always start a new thread at the end of the main and it will execute even after the main has completed.

Rox
  • 2,647
  • 15
  • 50
  • 85
  • I won't, the main method will wait for the thread to stop. If it was a daemon thread it will be terminated. – Jaco Van Niekerk Dec 21 '11 at 13:43
  • I disagree. Try this: **public class TestMain{ public static void main(String[] args) { System.out.println("main start"); new Thread(new Runnable(){ public void run() { while(true){ } } }).start(); System.out.println("main end"); } }** What I can see, "main end" is beeing printed which should mean the main method has completed. – Rox Dec 21 '11 at 13:57
  • I disagree. The JVM stops just before the return on the main method, waiting for the other threads to complete. It will therefore execute all statements in the main method, but the program will not terminate yet. – Jaco Van Niekerk Dec 21 '11 at 14:39
  • Could you show my a link from Oracle/Sun where it says so? – Rox Dec 22 '11 at 08:15
  • @JacoVanNiekerk : Even if you debug the program you can see that the main thread has completed and that the other thread is the only running! So I am sorry, I still think the main method completes unless you can prove I am wrong. – Rox Dec 22 '11 at 08:26
  • Ok fair enough. Thanks guys. – Jaco Van Niekerk Dec 22 '11 at 09:01
0

In C# you can create a new Thread and set IsBackground to false. Main will exit but the .NET Framework will keep your your application doing whatever it needs to be doing.

static void Main(string[] args)
{
    Thread thread = new Thread(() => {
        Thread.Sleep(10000);
        Console.WriteLine("Thread WriteLine");
    });

    thread.IsBackground = false;
    thread.Start();
    Console.WriteLine("Main WriteLine");
}
SomeWritesReserved
  • 1,075
  • 7
  • 17
-1

No, it is not possible. When the main method exists, the program terminates.

Jaco Van Niekerk
  • 4,180
  • 2
  • 21
  • 48