Systems Programming :: System Calls For Process Management I

Sunday, April 4, 2010 Posted by Kanishka Dilshan
Process Management System Calls

A process can be either program or a command. To perform a task process need CPU time, memory(address space), files & I/O devices. Every process is comprised of 4 attributes
  1. code (instructions)
  2. data
  3. stack
  4. unique process ID (PID)
getpid(), getppid() system calls

getpid() system call returns the process ID of the current process.
getppid() system call returns the parent's process ID of the current process

Sample program to demonstrate getpid() and getppid() functions



 1: #include <stdio.h>
 2: 
 3: int main()
 4: {
 5:  int pid=getpid(); //get current process ID
 6:  int ppid=getppid(); //get parent process ID
 7:  printf("PID (Current process ID) -> %d \n",pid);
 8:  printf("PPID (Parent process ID) -> %d \n",ppid);
 9:  return 0;
10: }

Output :



PPID is always greater than the PID.
The parent of all process is the init process its ID is always 1
to realize this execute following command and see the output
 ps -eo user,pid,ppid,stat,args
Output :
USER       PID  PPID STAT COMMAND
root         1     0 Ss   /sbin/init
root         2     0 S<   [kthreadd]
root         3     2 S<   [migration/0]
root         4     2 S<   [ksoftirqd/0]
root         5     2 S<   [watchdog/0]
root         9     2 S<   [events/0]
root        11     2 S<   [khelper]
root        12     2 S<   [kstop/0]
root        14     2 S<   [kintegrityd/0]
root        16     2 S<   [kblockd/0]
root        18     2 S<   [kacpid]
root        19     2 S<   [kacpi_notify]
root        20     2 S<   [cqueue]
root        21     2 S<   [ata/0]
...............................................


system() Library function and execl() system call
there is a considerable difference in between system() library function and execl() system call. when system() is executed a new process is created. But when execl() is executed the memory and instructions of original process is replaced by the new process and continues. So any instruction of original process will not be executed after the execl().

Lets consider following programs to identify the different between system() library function and execl() system call.

Program1: (system() library function)


1: #include <stdio.h>
2: 
3: int main()
4: {
5:  system("date");
6:  printf("I am here!\n");
7: }


Output 1:

Program 2: (execl() library function)


1: #include <stdio.h>
2: 
3: int main()
4: {
5:  execl("/bin/date","date",0);
6:  printf("I am here! \n");
7: }


Output 2:

When compare both output you can see the the  "I am here!" line is not printed in the output 2. The reason is execl() replaced the memory area and instructions of original process by the date utilities instructions and memory.

Note : you can use gcc or cc utilities (GNU C Compilers) to compile above examples. I've used gcc to compile above programs.

Labels:

Post a Comment