Are process ids non-negative in Linux?

Plazo picture Plazo · Mar 6, 2012 · Viewed 9.5k times · Source

I am implementing a syscall that is called in user-space, lets say by foo. The syscall accesses foo's task_struct ( throught the global pointer current), prints it's name and pid, then goes on to foo's parent-process, foo's parent's parent etc. Prints all their names and pids up to and including the init process's.

The pid=1 is reserved for init, the pid=0 is reserved for swapper.

According to swapper's task_struct, it's parent process is itself.

Swapper (or sched) always has pid=0 and is always init's parent-process?

Are all pids non-negative? Is it ok for me to make that assumption?

Answer

user401085 picture user401085 · Apr 4, 2012

To answer your questions more concisely:

  • IBM's Inside the Linux boot process describes the swapper process as the process having a PID value of 0. At startup this process runs /sbin/init (or another process given as parameter by the bootloader), which will typically be the process with PID 1.
  • In Unix systems PID values are allocated sequentially, starting from the first process and up to a maximum value specified by /proc/sys/kernel/pid_max. Therefore you can safely go under the assumption that all valid PIDs have a positive value, while negatives boil down to error values and such.
  • A good idea would also be accounting for zombie processes, since they can receive "special treatment" in the process tree when/if they are adopted by init.