Safe Way to Tell if Process is Running

Steve O'Hara-Smith ateve at sohara.org
Tue Dec 4 21:08:49 UTC 2012


On Tue, 04 Dec 2012 14:50:38 -0600
Martin McCormick <martin at x.it.okstate.edu> wrote:

> Robert Bonomi writes:
> > 'man 2  kill' tells all.
> 
> 	I believe that is the first or second time I have used
> Section 2. I appreciate the reminder. It looks like ps -p ###
> >/dev/null appears to do what I need without producing output
> 
> ps -p 54321 >/dev/null && date ran the date command if there was
> a process with that number and produced nothing if no process
> 54321 existed.

	That's not a certain test, ps can miss processes. Given that you
are working in C you would be better off calling kill directly rather than
spawning a process with system and risking picking up some odd
implementation of a command.

	if (-1 != kill(pid, 0)) {
		// Process exists
	} else if (EPERM == errno) {
		// No permission to signal process - belongs to someone else
	} else if (ESRCH == errno) {
		// Process does not exist
	} else {
		// Something weird and undocumented went wrong
	}

-- 
Steve O'Hara-Smith <ateve at sohara.org>


More information about the freebsd-questions mailing list