Advertisement
Guest User

Untitled

a guest
Mar 26th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.14 KB | None | 0 0
  1. //
  2. // myCLI.swift
  3. // CLI
  4. //
  5. // Created by Carlisle Miller on 6/03/2017.
  6. //
  7. // This program attempts to replicate the command line interface. It takes commands from the user
  8. // and prints the output to the terminal. It loops until the user enters 'exit'.
  9.  
  10.  
  11. import Foundation
  12.  
  13. private func WEXITSTATUS(_ status: CInt) -> CInt
  14. {
  15. return (status >> 8) & 0xff
  16. }
  17.  
  18. while (true) {
  19. let cmd: String = readLine()! // Reads command from user
  20.  
  21. if (cmd == "exit") {
  22. exit(EXIT_SUCCESS)
  23. }
  24.  
  25. var splitArray = cmd.components(separatedBy: " ") // Splits users string up into an array when a space is detected
  26. var cargv = splitArray.map { strdup($0) }
  27. cargv.append(nil)
  28.  
  29. defer {
  30. for arg in cargv { free(arg) }
  31. }
  32.  
  33. var pid = pid_t()
  34. let r: Int32 = posix_spawnp(&pid, splitArray[0], nil, nil, cargv, nil) // posix_spawnp creates new process and executes a commandq
  35.  
  36. if(r != 0) {
  37. let err: String = String(cString: strerror(r))
  38. print("posix_spawnp failed with: \(err)")
  39. exit(EXIT_FAILURE)
  40. }
  41.  
  42. var status: Int32 = 0
  43. let rv = waitpid(pid, &status, 0)
  44. if rv != -1 {
  45. print("Exit status: \(WEXITSTATUS(status))")
  46. }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement