{"id":2466,"date":"2016-01-11T07:23:47","date_gmt":"2016-01-11T13:23:47","guid":{"rendered":"http:\/\/dev.iachieved.it\/iachievedit\/?p=2466"},"modified":"2020-07-11T18:16:08","modified_gmt":"2020-07-11T23:16:08","slug":"trapping-signals-with-swift-on-linux","status":"publish","type":"post","link":"https:\/\/dev.iachieved.it\/iachievedit\/trapping-signals-with-swift-on-linux\/","title":{"rendered":"Trapping Signals with Swift on Linux"},"content":{"rendered":"<p><b>Update:<\/b>  Folks have figured out how to use <code>sigaction<\/code> which is the preferred way of catching a signal.  Jump down to read all about it, both <code>signal<\/code> and <code>sigaction<\/code> methods work!<\/p>\n<p>Unix applications frequently have a need to catch, or trap, <a href=\"https:\/\/en.wikipedia.org\/wiki\/Unix_signal\">signals<\/a>.  For example, many daemons will reread their configuration file upon receipt of the <code>SIGHUP<\/code> signal.  A client interface may catch CTRL-C and print <code>Are you sure you want to quit? [yN]<\/code>.<\/p>\n<p>This can be accomplished in Swift on Linux as well by using the <a href=\"http:\/\/man7.org\/linux\/man-pages\/man2\/signal.2.html\"><code>signal<\/code><\/a> function from <code>Glibc<\/code>.  The code, which is a play on Adam Sharp&#8217;s <a href=\"https:\/\/gist.github.com\/sharplet\/d640eea5b6c99605ac79\">gist<\/a>:<\/p>\n<pre class=\"lang:swift\">\nimport Glibc\n\nenum Signal:Int32 {\n  case HUP    = 1\n  case INT    = 2\n  case QUIT   = 3\n  case ABRT   = 6\n  case KILL   = 9\n  case ALRM   = 14\n  case TERM   = 15\n}\n\ntypealias SignalHandler = __sighandler_t\n\nfunc trap(signum:Signal, action:SignalHandler) {\n  signal(signum.rawValue, action)\n}\n\ntrap(.INT) { signal in\n  print(\"Intercepted signal:  \\(signal)\")\n}\n\nselect(0, nil, nil, nil, nil) \/\/ Wait around for CTRL-C\n<\/pre>\n<p>Run with <code>swift<\/code> or compile and execute using <code>swiftc<\/code>.  The application will wait at the <code>select<\/code> statement.  Pressing CTRL-C will generate a <code>SIGINT<\/code> and the trap routine will execute (and end the application).<\/p>\n<p>To be clear, the application did not exit because the trap closure was executed.  The exit occurred because flow of control transferred from the closure to <i>after<\/i> the <code>select<\/code>.  Think of the line after the <code>select<\/code> as an implicit <code>exit(0)<\/code>.  If you rewrite this as<\/p>\n<pre class=\"lang:swift\">\nwhile true {\n  select(0, nil, nil, nil, nil)\n}\n<\/pre>\n<p>then the application will not exit after the signal handler executes.<\/p>\n<p><b>Note:<\/b>  The <code>Signal<\/code> enumeration is but a small subset of the various signals.  Check out <a href=\"http:\/\/man7.org\/linux\/man-pages\/man7\/signal.7.html\"><code>man 7 signal<\/code><\/a> for a complete list.<\/p>\n<h3>Pretty Printing<\/h3>\n<p>There&#8217;s no need to add another integer-to-string translation table to get the type of signal received.  <code>strsignal<\/code> is a handy function to get a human-friendly string name for the signal:<\/p>\n<pre class=\"lang:swift\">\ntrap(.INT) { signal in\n  if let signalName = String.fromCString(strsignal(signal)) {\n    print(\"Intercepted signal:  \\(signalName)\")\n  } else {\n    print(\"Intercepted signal:  \\(signal)\")\n  }\n}\n<\/pre>\n<h3>Trailing Closures<\/h3>\n<p><i>Trailing closures<\/i> are one of those syntactical goodies that make Swift a joy to program in.  Your first exposure to them is <i>probably<\/i> implementing a callback function to an HTTP GET request:<\/p>\n<pre class=\"lang:swift\">\nlet request = HTTPRequest(.GET, url:\"http:\/\/someappserver\/somerestapi\/somerestresource\"){\n  response, error in \n  \/\/ do some stuff with the response\n}\nrequest.request()\n<\/pre>\n<p>The code between the braces is <i>actually<\/i> the <i>last<\/i> parameter to the <code>HTTPRequest<\/code> class initializer.  The parameter signature is likely to be <code>(HTTPResponse, NSError) -&gt; Void<\/code>.  Nothing requires you to code this in the form of the trailing closure, but it&#8217;s frequently nice to.  Just remember that a trailing closure can only be used when the function to be called is the <i>last<\/i> parameter in the function signature.  Those are the rules.<\/p>\n<p>We of course use this feature in our routine:<\/p>\n<pre class=\"lang:swift\">\ntypealias SignalHandler = __sighandler_t\n\nfunc trap(signum:Signal, action:SignalHandler) {\n  signal(signum.rawValue, action)\n}\n\ntrap(.INT) { signal in\n  print(\"Intercepted signal:  \\(signal)\")\n}\n<\/pre>\n<p>The trailing closure syntax is used to specify the signal handler which must adhere to the <code>__signalhanlder_t<\/code> function signature.  This signature is simply <code>(Int32) -&gt; Void<\/code>, which is what our trailing closure is.<\/p>\n<h3>What about `sigaction`?<\/h3>\n<p>Truth be told, we ought to be using <a href=\"http:\/\/man7.org\/linux\/man-pages\/man2\/sigaction.2.html\"><code>sigaction<\/code><\/a> rather than <code>signal<\/code>.  The man page says so, and everyone knows better than to argue with a man page.<\/p>\n<pre class=\"crayon:false\">\nThe behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux.   Avoid  its  use:  use sigaction(2) instead.\n<\/pre>\n<p>Unfortunately I haven&#8217;t figured out <i>how<\/i> to use <code>sigaction<\/code> with Swift on Linux.  There are two <code>sigaction<\/code> definitions in Glibc.  One is for the <code>sigaction<\/code> structure (<code>struct sigaction<\/code>) and the other is for the <code>sigaction<\/code> function.  Swift can&#8217;t seem to distinguish between the two, and only the function is surfaced.  Without the structure definition its difficult to call <code>sigaction<\/code>.  Perhaps it is possible to write our own <code>struct sigaction<\/code> definition and somehow trick Swift into thinking it can be passed into the <code>sigaction<\/code> function.  I haven&#8217;t tried, but if someone out there figures it out, leave a comment!<\/p>\n<p><b>Hold the phone!<\/b>  An update on <code>sigaction<\/code> from Robert (see comments) allows us to use <code>sigaction<\/code>!  We&#8217;ve taken his code (thanks Robert) and updated it a bit:<\/p>\n<pre class=\"lang:swift\">\nimport Glibc\n\nenum Signal:Int32 {\ncase HUP    = 1\ncase INT    = 2\ncase QUIT   = 3\ncase ABRT   = 6\ncase KILL   = 9\ncase ALRM   = 14\ncase TERM   = 15\n}\n\ntypealias SigactionHandler = @convention(c)(Int32) -> Void\n               \nlet hupHandler:SigactionHandler = { signal in\n  print(\"Received HUP signal, reread config file\")\n}\n                  \nfunc trap(signum:Signal, action:SigactionHandler) {\n  var sigAction = sigaction()  \n                    \n  sigAction.__sigaction_handler = unsafeBitCast(action, sigaction.__Unnamed_union___sigaction_handler.self)\n                    \n  sigaction(signum.rawValue, &sigAction, nil)\n}\n                  \n\/\/ This method works\ntrap(.INT) { signal in\n  print(\"Received INT signal\")\n  exit(0)\n}\n\n\/\/ And this works of course\ntrap(.HUP, action:hupHandler)\n\nwhile true {\n  select(0, nil, nil, nil, nil)\n}\n<\/pre>\n<p>Try it out!<\/p>\n<h3>One Last Example<\/h3>\n<p>I mentioned above that the trailing closure didn&#8217;t <i>have<\/i> to be used to provide the signal handler routine.  In this code we declare a single function <code>sighandler<\/code> with a <code>(Int32) -&gt; Void<\/code> signature and then use it to trap <code>SIGINT<\/code>, <code>SIGHUP<\/code>, and <code>SIGUSR1<\/code>.<\/p>\n<pre class=\"lang:swift\">\nfunc sighandler(signal:Int32) {\n  if let signalName = String.fromCString(strsignal(signal)) {\n    print(\"Intercepted signal:  \\(signalName)\")\n  } else {\n    print(\"Intercepted signal:  \\(signal)\")\n  }\n}\n\ntrap(.INT,  action:sighandler)\ntrap(.USR1, action:sighandler)\ntrap(.HUP,  action:sighandler)\n<\/pre>\n<figure id=\"attachment_2478\" aria-describedby=\"caption-attachment-2478\" style=\"width: 564px\" class=\"wp-caption aligncenter\"><a href=\"https:\/\/dev.iachieved.it\/iachievedit\/wp-content\/uploads\/2016\/01\/Untitled-window_009.png\" rel=\"attachment wp-att-2478\"><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/dev.iachieved.it\/iachievedit\/wp-content\/uploads\/2016\/01\/Untitled-window_009.png\" alt=\"Handling Signals\" width=\"564\" height=\"340\" class=\"size-full wp-image-2478\" \/><\/a><figcaption id=\"caption-attachment-2478\" class=\"wp-caption-text\">Handling Signals<\/figcaption><\/figure>\n","protected":false},"excerpt":{"rendered":"<p>Update: Folks have figured out how to use sigaction which is the preferred way of catching a signal. Jump down to read all about it, both signal and sigaction methods work! Unix applications frequently have a need to catch, or trap, signals. For example, many daemons will reread their configuration file upon receipt of the [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":3108,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[19,5],"tags":[],"class_list":["post-2466","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linux","category-swift"],"_links":{"self":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/2466"}],"collection":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/comments?post=2466"}],"version-history":[{"count":19,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/2466\/revisions"}],"predecessor-version":[{"id":4169,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/posts\/2466\/revisions\/4169"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/media\/3108"}],"wp:attachment":[{"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/media?parent=2466"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/categories?post=2466"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/dev.iachieved.it\/iachievedit\/wp-json\/wp\/v2\/tags?post=2466"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}