local posix = require "posix"

module("lua_ostasks.posix", package.seeall)

---
--
function start (task, ...)
	local pid = posix.fork()
	if pid == 0 then
		-- this is now the forked process (child)
		if task.working_directory then posix.chdir(task.working_directory) end

		-- If execp fails (i.e. command not found) then at least print an error.
		-- A proper solution implies notifying the parent of this error condition, using pipes as described here:
		-- http://stackoverflow.com/questions/1584956/how-to-handle-execvp-errors-after-fork
		assert(posix.execp(task.task, ...))
	else
		return pid
	end
end

---
--
function kill (pid)
	local ok, err, errno = posix.kill(pid)
	if not ok then
		return nil, err
	end
	local timeleft, step = 10, 2
	ok, err, errno = posix.wait(pid, posix.WNOHANG)
	while ok == 0 and timeleft > 0 do
		io.stderr:write( ("Pid %d hasn't stopped yet. Wait %d more seconds.\n"):format(pid, timeleft) )
		posix.sleep(step)
		ok, err, errno = posix.wait(pid, posix.WNOHANG)
		timeleft = timeleft - step
	end
	if ok == 0 then
		io.stderr:write( ("Pid %d hasn't stopped. Will send SIGKILL signal.\n"):format(pid) )
		ok, err, errno = posix.kill(pid, posix.SIGKILL)
	end
	if not ok then
		return nil, err
	end	
	return true
end

---
-- 
function rmfile (filename)
	posix.unlink(filename)
end
