Showing posts with label unix. Show all posts
Showing posts with label unix. Show all posts

Saturday, December 4, 2010

exec() Family System Calls

The exec family of functions shall replace the current process image with a new process image.

execl()

Synopsis

int execl(const char *path, const char *arg0, const char *arg1, const char *arg2, ... const char *argn, (char *) 0);

A command (with the path to the command e.g /bin/ls) and the required arguments are passed to the function."arg0" is the command to be executed. Function arguments are null terminated strings(The list of arguments is terminated by NULL).

Example

#include <unistd.h>
 main()
 {
    execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
 }


execlp()

A command (path to the command will be resolved by the function itself) and the required arguments are passed to the function."arg0" is the command to be executed.

Example

#include <unistd.h>
 main()
 {
    execlp("ls", "ls", "-r", "-t", "-l", (char *) 0);
 }


execv()

Synopsis

int execv(const char *path, char *const argv[]);

Same as the execl function except now the arguments will be passed into a null terminated char pointer array."arg[0]" is the command to be executed.

Example

#include <unistd.h>
 main()
 {
    char *args[] = {"/bin/ls", "-r", "-t", "-l", (char *) 0 };
  
    execv("/bin/ls", args);
 
 }

Thursday, December 2, 2010

fork() System Call

System call fork() is used to create processes, the newly created process will be the child of the calling process parent. Unix will make an exact copy of the parent's address space and give it to the child. Therefore, the parent and child processes have separate address spaces.

fork() returns a process ID AKA PID, there are three instances;

  1. if PID < 0, fork() returns a negative value, the creation of a child process was unsuccessful.


  2. if PID ==0, fork() returns a zero to the newly created child process.


  3. if PID > 0, fork() returns a positive value, the process ID of the child process, to the parent.


After a successful call of fork(),unix makes two identical copies of address spaces, one for the parent and the other for the child. Both processes will start their execution at the next statement following the fork() call.



Since both processes have identical but separate address spaces;
  • Variables initialized before the fork() call have the same values in both address spaces.
  • Modifications done in each process will be independent.
Example
#include <signal.h>
#include <stdio.h>

void main() 
{
 int pid;

 printf("Parent process ID %d \n",getpid());

 pid = fork();

  if (pid==0) {
   printf("Child process ID %d \n",getpid());
    int x;
    printf("Enter Value : ");
    scanf("%d",&x);
    printf("Entered Value : %d",x);
  } else if (pid > 0) {
   sleep(5);// parent stops execution for 5 seconds
   printf("Parent process ID %d \n",getpid());

  }

}