Optil.io help - handling signals

Below there are examples of not optimal programs solving the tutorial problem with correct signals handling. More information about signals handling can be found in help.

Currently, there is an example for C, C++ (with CMake, with CPLEX), Python 2, Python 3, Java, Haskell, VB.NET. If you need an example in some other language, let us now.

C

Remember about a volatile keyword to make sure that the optimizer will not remove the variable from the for loop.

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <math.h>
 
volatile sig_atomic_t tle = 0;
int n, i;
float worker;
 
void term(int signum)
{
    tle = 1;
}
 
int main(int argc, char *argv[])
{
    struct sigaction action;
    memset(&action, 0, sizeof(struct sigaction));
    action.sa_handler = term;
    sigaction(SIGTERM, &action, NULL);
 
    scanf("%d", &n);
    for (i = 0; i < n - 1 && !tle; i++)
      worker += sqrt((float)i);
    printf("%d\n", (int)(worker/n));
 
    return 0;
}

C++

Remember about a volatile keyword to make sure that the optimizer will not remove the variable from the for loop.

#include <signal.h>
#include <unistd.h>
#include <cstring>
#include <iostream>
#include <cmath>
 
using namespace std;

volatile sig_atomic_t tle = 0;
int n;
float worker;
 
void term(int signum)
{
    tle = 1;
}
 
int main(int argc, char *argv[])
{
    struct sigaction action;
    memset(&action, 0, sizeof(struct sigaction));
    action.sa_handler = term;
    sigaction(SIGTERM, &action, NULL);
 
    ios_base::sync_with_stdio(false);
    cin >> n;
    for (int i = 0; i < n - 1 && !tle; i++)
      worker += sqrt((float)i);
    cout << (int)(worker / n) << endl;
 
    return 0;
}

If you want to use CMake package you have to add the following content to the CMakeLists.txt file, save the code presented above in tut.cpp file and pack both of them to the Tut.tgz archive (beware of casing).

cmake_minimum_required (VERSION 2.6)
project (Tut)
add_executable (Tut tut.cpp)

Python 2

import signal
import time
from math import sqrt

class Killer:
  exit_now = False
  def __init__(self):
    signal.signal(signal.SIGINT, self.exit)
    signal.signal(signal.SIGTERM, self.exit)

  def exit(self,signum, frame):
    self.exit_now = True

killer = Killer()
n = int(input())
worker = 0.0
for i in xrange(0,n):
  worker += sqrt(i)
  if killer.exit_now:
    break

print i
print int(worker / n)

Python 3

import signal
import time
from math import sqrt

class Killer:
  exit_now = False
  def __init__(self):
    signal.signal(signal.SIGINT, self.exit)
    signal.signal(signal.SIGTERM, self.exit)

  def exit(self,signum, frame):
    self.exit_now = True

killer = Killer()
n = int(input())
worker = 0.0
for i in range(0,n):
  worker += sqrt(i)
  if killer.exit_now:
    break

print(int(worker / n))

Java

Java compiler notifies that the signals API is deprecated. However, it is not planned to be removed in Java 9 and it is the only working way to handle signals on the server.

import java.util.Scanner;
import sun.misc.Signal;
import sun.misc.SignalHandler;
import java.util.concurrent.CountDownLatch;

public class Tut
{
    public static void main(final String[] args) throws InterruptedException
    {
        Scanner in = new Scanner(System.in);
        final CountDownLatch exit_now = new CountDownLatch(1);
        double worker = 0.0;
        int n;

        SignalHandler termHandler = new SignalHandler()
        {
            @Override
            public void handle(Signal sig)
            {
                System.out.println("Terminating");
                exit_now.countDown();
            }
        };
        Signal.handle(new Signal("TERM"), termHandler);

        n = in.nextInt();
        for (int i = 0; i < n && exit_now.getCount() == 1; i++)
        {
            worker += Math.sqrt((double)i);
        }
        System.out.print((int)(worker / n));
    }
}

Haskell

This code does not implement signals handling. If you know how to implement it in Haskell, please send us an example.

main = do
  n <- getLine
  let v = read n :: Int
  print (v-1)

C++ with CPLEX

This code does not implement signals handling yet.

#include <ilcplex/ilocplex.h>
ILOSTLBEGIN

int
main (int argc, char **argv)
{
   int n;
   IloEnv   env;
   IloModel model(env);
   IloNumVarArray var(env);
   IloRangeArray con(env);
   IloCplex cplex(model);
   cplex.setOut(env.getNullStream());
   
   cin >> n;
   var.add(IloNumVar(env, 0, 1000000000, ILOINT));
   model.add(IloMaximize(env, var[0]));
   con.add(var[0] <= (n - 1));
   model.add(con);

   cplex.solve();
   cout << cplex.getObjValue() << endl;

   env.end();
   return 0;
}

VB.NET

This code does not implement signals handling. If you know how to implement it in VB.NET at Mono, please send us an example.

Module Tutorial

    Sub Main()
        Dim line = Console.ReadLine()
        Dim n = Integer.Parse(line)
        Console.WriteLine(n - 1)
    End Sub

End Module