Skip to content

Commit

Permalink
fix clean up memory in log task executor
Browse files Browse the repository at this point in the history
  • Loading branch information
miguelangel-dev committed Sep 19, 2019
1 parent 0515b3f commit 8229880
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions Source/Swiftline/CommandExecutor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,27 +96,28 @@ class LogTaskExecutor: TaskExecutor {

func execute(_ commandParts: [String]) -> ExecutorReturnValue {
let argv: [UnsafeMutablePointer<CChar>?] = commandParts.map{ $0.withCString(strdup) }
defer { for case let arg? in argv { free(arg) } }

var pid: pid_t = 0
var childFDActions: posix_spawn_file_actions_t? = nil
let outputPipe: Int32 = 69
let outerrPipe: Int32 = 70

defer {
for case let arg? in argv { free(arg) }
posix_spawn_file_actions_addclose(&childFDActions, outputPipe)
posix_spawn_file_actions_addclose(&childFDActions, outerrPipe)
posix_spawn_file_actions_destroy(&childFDActions)
}

posix_spawn_file_actions_init(&childFDActions)
posix_spawn_file_actions_addopen(&childFDActions, outputPipe, stdoutLogPath, O_CREAT | O_TRUNC | O_WRONLY, ~0)
posix_spawn_file_actions_addopen(&childFDActions, outerrPipe, stderrLogPath, O_CREAT | O_TRUNC | O_WRONLY, ~0)
posix_spawn_file_actions_adddup2(&childFDActions, outputPipe, 1)
posix_spawn_file_actions_adddup2(&childFDActions, outerrPipe, 2)

var result = posix_spawn(&pid, argv[0], &childFDActions, nil, argv + [nil], nil)
guard result == 0 else { return (Int(1), "", "") }

guard result == 0 else { return (Int(result), "", "") }
waitpid(pid, &result, 0)
posix_spawn_file_actions_addclose(&childFDActions, outputPipe)
posix_spawn_file_actions_addclose(&childFDActions, outerrPipe)
posix_spawn_file_actions_destroy(&childFDActions)


let (stdout, stderr) = read(outputPath: stdoutLogPath, outerrPath: stderrLogPath)
removeFiles(stdoutLogPath, stderrLogPath)
write(atPath: logPath, content: "\(stdout)\n\(stderr)")
Expand Down

0 comments on commit 8229880

Please sign in to comment.