11

I have two Linux systems communicating over sockets (Desktop and ARM-based development board).

I want to restart (or reset) my client application (running on a development board) when server sends a particular predefined message. I don't want to restart (reboot) Linux, I just want that client application restart itself automatically.

I am unable to understand how it should be done.

5 Answers 5

9

Make your client exec /proc/self/exe when it receives that paticular message. You don't need to know where the executable actually resides in the file system. And you can reuse main()'s argv to construct a new argument vector.

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
        char buf[32] = {};
        char *exec_argv[] = { argv[0], buf, 0 };
        int count = argc > 1 ? atoi(argv[1]) : 0;

        printf("Running: %s %d\n", argv[0], count);
        snprintf(buf, sizeof(buf), "%d", count+1);
        sleep(1);

        execv("/proc/self/exe", exec_argv);

        /* NOT REACHED */
        return 0;
}

This restart.c runs like this:

$ gcc restart.c 
$ ./a.out 3
Running: ./a.out 3
Running: ./a.out 4
Running: ./a.out 5
6

The normal way to do this is to let your program exit, and use a monitoring system to restart it. The init program offers such a monitoring system. There are many different init programs (SysVinit, BusyBox, Systemd, etc.), with completely different configuration mechanisms (always writing a configuration file, but the location and the syntax of the file differs), so look up the documentation of the one you're using. Configure init to launch your program at boot time or upon explicit request, and to restart it if it dies. There are also fancier monitoring programs but you don't sound like you need them. This approach has many advantages over having the program do the restart by itself: it's standard, so you can restart a bunch of services without having to care how they're made; it works even if the program dies due to a bug.

There's a standard mechanism to tell a process to exit: signals. Send your program a TERM signal. If your program needs to perform any cleanup, write a signal handler. That doesn't preclude having a program-specific command to make it shut down if you have an administrative channel to send it commands like this.

2

If the client application is a Linux service, it can be restarted with this command:

service <clientapp> restart

or forced to reload its configuration:

service <clientapp> reload
service <clientapp> force-reload

If, more likely, it's a custom application, it needs to have embedded in its code the feature to restart itself or reload its configuration upon reception of a signal or event. Failing to do so, as a last resort you can always kill the client app:

pkill -9 <clientapp>

and restart again, but it's ugly as it leaves the app in an undetermined state.

5
  • 2
    Unless the application is already in a bogus state, the -9 argument to pkill is not needed, not using it should allow the application to cleanly stop itself. Jun 6, 2015 at 11:04
  • @dr01 If application is not a service then how to restart it?
    – Saad Rafey
    Jun 6, 2015 at 11:14
  • @SaadRafey: it's written in my answer, the capability to restart itself cleanly or to reload the configuration must be written in the code.
    – dr_
    Jun 6, 2015 at 11:59
  • I think this only works with OLD UBUTNU versions
    – user254419
    Sep 10, 2018 at 19:09
  • @noone Not at all, that's the standard SystemV command for service management. Now, it's true that most modern versions of distros use Systemd.
    – dr_
    Sep 11, 2018 at 6:57
0

If you have pid of the program then you can use "Kill PID" to terminate the application. I have tried to save the complete instance of the application before closing but this process is very tedious. You can simply use terminal for starting the application. Like if you wish to start firefox simply typing in terminal will open your application. But if you wish to restart from your C++ script. This can be done by simply piping your command to shell.

I have made a function for executing a command in a shell:

string ExecCmd(string command) {
  char buffer[128];
  string cmd_out = "";

  // open pipe to file and execute command in linux terminal
  FILE* pipe = popen(command.c_str(), "r");
  if (!pipe)
    return "popen failed!";

  // read till end of process:
  while (!feof(pipe)) {
    // read output of the sent command and add to result
    if (fgets(buffer, 128, pipe) != NULL)
      cmd_out += buffer;
  }
  pclose(pipe);
  // returns the output of terminal in string format
  return cmd_out;
}

Then for killing the process and restarting it I used:

void RestartApplication(string proc_id) {
  // kill the running process
  ExecCmd("kill " + proc_id);

  // restart the application by giving the name of your program
  ExecCmd("nohup program_name >program_name.log &");
}

I have used nohup command because it release the terminal after command execution. Now to call run this script you can write under your main program thread:

void main(){
 RestartApplication(PID); // pass PID of your application to be restarted
}
0

Sometimes a process will hang and although it appears to be running it isn't actually doing anything, perhaps owing to a code fault that only triggers occasionally. Just about the only thing that can be done is to restart, but this means first finding and then killing the hung process.

I had the problem that a process (a Python server) was hanging from time to time without quitting. I dealt with it by forcing a kill/restart every few hours. Here's the script called by cron; the program in question is myapp.py. The strange grep prevents grep from returning its own process id.

#!/bin/sh

# This cron script restarts the server
# Look for a running instance of myapp.py
p=$(ps -eaf | grep "[m]yapp.py")
# Get the second item; the process number
n=$(echo $p | awk '{print $2}')
# If it's not empty, kill the process
if [ "$n" ]
then
   kill $n
fi
# Start a new instance
python3 myapp.py
2

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .