How to run Apache in foreground

You can run Apache in foreground using command:

apache2ctl -D FOREGROUND

But it is not that simple. While the above command works, Apache process will terminate once it receives SIGWINCH signal from the operating system with following error message:

... AH00170: caught SIGWINCH, shutting down gracefully

SIGWINCH is codename for “Signal Window Change”. A process receives SIGWINCH signal whenever the window it is running under is resized. It can also occur during other GUI events like when screen goes blank after certain time of inactivity.

The reason Apache behaves this way is because Apache misuses SIGWINCH signal to do a graceful shutdown (as mentioned in this link).

One partial workaround is to keep the terminal window in inactive workspace when you do not need . Operating system like Ubuntu has workspace which allows user to organize application windows. In Ubuntu 22.04, user can navigate to another workspace using Ctrl+Alt+Left/Right keys and can move the active window to another workspace using Shift+Ctrl+Alt+Left/Right keys. This prevents user from accidentally resizing the window. But, it does not prevent from shutdown due to screen going blank. Also, this does not allow to view the Apache logs which may be the whole point of running Apache server in foreground in first place.

Another workaround is to create a program that starts Apache process and restart it whenever Apache process shutdown due to SIGWINCH signal. I have created a Node.js script that does exactly that. Copy and save the code below in a file (apache-foreground.js) and run it using Node.js (node apache-foreground.js). For this to work, you need to have Node.js installed.

const child_process = require('child_process');

// SIGTERM listener has been set because Apache process can emit SIGTERM in parent process
// and by setting SIGTERM listener the default behavior of exiting the process is overridden
process.on('SIGTERM', () => {
});

// user can press Ctrl+C to close the program
process.on('SIGINT', () => {
  process.exit(0);
});

let apacheProc;

function startApacheServer()
{
  apacheProc = child_process.spawn(
    'apache2ctl', ['-D', 'FOREGROUND'],
    {
      stdio: [0,0,0],
    }
  );

  apacheProc.on('close', () => {
    console.log('\nRestarting Apache server\n');
    startApacheServer();
  });
}

startApacheServer();

By using this Node.js script, whenever SIGWINCH signal occurs, Apache server is automatically restarted as shown below. Also, user can press Ctrl + C to manually stop Apache server.

... AH00170: caught SIGWINCH, shutting down gracefully

Restarting Apache server

... AH00163: Apache/2.4.52 (Ubuntu) PHP/8.1.2-1ubuntu2.11 configured -- resuming normal operations
... AH00094: Command line: '/usr/sbin/apache2 -D FOREGROUND'