UNIX Multiprocess Fork Exec
UNIX Multiprocess Fork Exec
multi-process programming
using fork and execs
By
CHITRAKANT BANCHHOR
IT, SCOE, Pune
References
1. W. Richard Stevens , “Advanced Programming in the UNIX® Environment”, Addison
Wesley Professional .
getpid();
getppid();
#include<stdio.h>
#include<unistd.h>
int main()
{
printf(“The process id =%ld\n”, (long) getpid() );
printf(“The parent id =%ld\n”, (long) getppid() );
return 0;
}
fork(): creating new process
#include<sys/ types.h>
#include<unistd.h>
pid_t fork(void);
fork returns
In child : 0
-1 : on errors
Main Memory
if (pid == 0) { Secondary Memory
printf ( “Child Process\n”);
}
Parent Process
Address else {
Space printf ( “Parent Process\n”);
}
pid = fork ();
if (pid == 0) {
printf ( “Child Process\n”);
}
if (pid == 0) {
else {
printf ( “Child Process\n”);
printf ( “Parent Process\n”);
}
}
Child Process else {
Address
Space printf ( “Parent Process\n”);
}
wait() function
#include<sys/ types.h>
#include<sys/ wait.h>
Return value from wait is the pid that matches the return termination
status.
- 1 on error.
Assignment--1
Assignment
1 int execle (
const char* pathname,
const char* arg0,
…………..
(char*)0,
char *const envp[ ]
);
2 int execl (
const char* pathname,
const char* arg0,
…………..
(char*)0,
);
3
int execv (
const char* pathname,
char* const argv[ ]
);
4
int execlve(
const char* pathname,
char* const argv[ ],
char * const envp[ ]
);
5 int execlp (
const char* filename,
const char* arg0,
…………………….,
(char*)0
);
6
int execlvp (
const char* filename,
char* const argv[ ],
);
1. execl():execute and leave
#include<unistd.h>
execl(path,arg0,arg1,…,argn,0);
main()
{
printf(“The output of date command\n”);
execl(“/bin/date”, ”date”, (char*)0 );
printf(“It was the date\n”);
}
Example: Executing new program
int main()
{
int pid;
/* fork another process */
pid = fork();
if (pid == 0) {
execl(“/bin/ls”,”ls”,”-l”,0);
}
else {
/* parent will wait for the child to complete */
wait(NULL);
printf("Child Complete");
exit(0);
}
}
execv.c int execv ( const char* pathname, char* const argv[ ] ) ;
pid = fork ( ) ;
if ( pid == 0 ) {
execv ( “/bin/ls” , args );
}
else {
wait ( NULL );
printf ( “Parent process\n” );
}
}
execv--1
execv
execv1.c
Thank You!