Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // myCLI.swift
- // CLI
- //
- // Created by Carlisle Miller on 6/03/2017.
- //
- // This program attempts to replicate the command line interface. It takes commands from the user
- // and prints the output to the terminal. It loops until the user enters 'exit'.
- import Foundation
- private func WEXITSTATUS(_ status: CInt) -> CInt
- {
- return (status >> 8) & 0xff
- }
- while (true) {
- let cmd: String = readLine()! // Reads command from user
- if (cmd == "exit") {
- exit(EXIT_SUCCESS)
- }
- var splitArray = cmd.components(separatedBy: " ") // Splits users string up into an array when a space is detected
- var cargv = splitArray.map { strdup($0) }
- cargv.append(nil)
- defer {
- for arg in cargv { free(arg) }
- }
- var pid = pid_t()
- let r: Int32 = posix_spawnp(&pid, splitArray[0], nil, nil, cargv, nil) // posix_spawnp creates new process and executes a commandq
- if(r != 0) {
- let err: String = String(cString: strerror(r))
- print("posix_spawnp failed with: \(err)")
- exit(EXIT_FAILURE)
- }
- var status: Int32 = 0
- let rv = waitpid(pid, &status, 0)
- if rv != -1 {
- print("Exit status: \(WEXITSTATUS(status))")
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement