8

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?

Plazo
  • 81
  • 1
  • 1
  • 4

3 Answers3

7

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.
Community
  • 1
  • 1
3

It is always positive or 0. The kernel sources define it to be of pid_t type which, afaik is considered to be an unsigned (although it is defined as signed in order to be able to make calls such as fork return negative numbers in case of errors).

Mihai Maruseac
  • 20,967
  • 7
  • 57
  • 109
  • Thanks I will check immediately how pid_t is defined. – Plazo Mar 06 '12 at 13:09
  • 1
    I think it is signed, `fork` returns `pid_t` which can be `-1`. Also I think I remember seeing it in the some header. Need to check. Ofc, this doesn't mean that the process id can be negative – another.anon.coward Mar 06 '12 at 13:12
  • It's signed, just looked into it. But it is so in order to return errors :D – Mihai Maruseac Mar 06 '12 at 13:18
  • so it will return an error to the parent process using a negative pid of -1? but a process will never "actually" have negative id – Plazo Mar 06 '12 at 13:21
  • fork's Return Value On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately. – Plazo Mar 06 '12 at 13:29
  • 1
    Careful. A valid pid is never zero – Guido Mar 20 '12 at 03:44
2

Yes, they are actually always positive.

You can verify this by several POSIX system calls, such as wait, that use negative values to represent things such as all child processes of your own, or the like, and only positive values represent valid PID's.

Example: http://linux.die.net/man/2/wait

Guido
  • 2,571
  • 25
  • 37