0% found this document useful (0 votes)
14 views7 pages

Labsheet 4

The document outlines a lab sheet focused on executing programs using the exec() system call in C, including various exec functions and their parameters. It provides detailed instructions for writing multiple C programs that demonstrate process creation, command execution, and handling command line inputs. Additionally, it includes hints for using waitpid() for process synchronization and manipulating the current working directory.

Uploaded by

aachalladdha03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views7 pages

Labsheet 4

The document outlines a lab sheet focused on executing programs using the exec() system call in C, including various exec functions and their parameters. It provides detailed instructions for writing multiple C programs that demonstrate process creation, command execution, and handling command line inputs. Additionally, it includes hints for using waitpid() for process synchronization and manipulating the current working directory.

Uploaded by

aachalladdha03
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Lab-Sheet-4

Problem Sheet #5

Objective: To learn execution of a (new)programme (process) using exec()system call,

and other process execution functions and

To read Commandline input in c prg

==================

exec functions are used to execute a prg, by replacing the current process image with a new process
image in the calling process.

family of exec() syscalls-

int execl(const char *path, const char *arg, ...);

int execlp(const char *file, const char *arg, ...);

int execle(const char *path, const char *arg,..., char * const envp[]);

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

int execvp(const char *file, char *const argv[]);

int execvpe(const char *file, char *const argv[],char *const envp[]);

grouping of above functions-

execv(), execvp(),execvpe() -array of pointers to null-terminated strings(v)

execl(), execlp(), execle() -list of one or more pointers (l)

execle(),execvpe() -environment of the executed program (e)

execlp(), execvp(), execvpe() - searching(path) for an executable file (p)

The exec() family of functions replaces the current process image with a new process image.

execl(), execlp(), and execle() The const char *arg and subsequent ellipses in the functions can be
thought of as arg0, arg1, ..., argn.

Together they describe a list of one or more pointers to null-terminated strings that represent the
argument list available to the executed

program. The first argument, by convention, should point to the filename associated with the file
being executed. The list of arguments must

be terminated by a NULL pointer, and, since these are variadic functions, this pointer must be cast
(char *) NULL.
The execv(), execvp(), and execvpe() functions provide an array of pointers to null-terminated strings
that represent the argument list

available to the new program. The first argument, by convention, should point to the filename
associated with the file being executed.

The array of pointers must be terminated by a NULL pointer.

The execle() and execvpe() functions allow the caller to specify the environment of the executed
program via the argument envp. The envp

argument is an array of pointers to null-terminated strings and must be terminated by a NULL


pointer. The other functions take the

environment for the new process image from the external variable environ in the calling process.

The execlp(), execvp(), and execvpe() functions duplicate the actions of the shell in searching for an
executable file if the specified

filename does not contain a slash (/) character. The file is sought in the colon-separated list of
directory pathnames specified in the PATH environment variable. If this variable isn't
defined, the path list defaults to the current directory followed by the list of directories

If the specified filename includes a slash character, then PATH is ignored, and the file at the specified
path-name is executed.(These functions works with absolute path)

The exec() functions return only if an error has occurred. The return value is -1, and errno is set to
indicate the error.

By executing function " execl("","",NULL) " in current process, execl() will load programme image of
the programme(file) specified as parameter in execl().

(if p present in exec function name then the $PATH variable is used to find location of prg)

==== Commandline input

In c prg format of main function- int main(int argc, char []*argv)

It returns to calling function - number of strings , including the command, and the strings entered
from commandline

=====

NOTE- keep source file name as lab-sheetnumber-questionnumber.c


keep output(executable) file name as lab-sheetnumber-questionnumber

(for lab-sheet-4 : outputfilename format-source file- lab-4-n.c , ouput file- lab-4-n ,where n=1 to 9)

(in case of part ,for example, Q1a, filename will be lab-4-1a.c (source) and lab-4-1a (output)

Include following header files- stdio.h, stdlib.h ,sys/types.h, sys/wait.h and unistd.h

=====Problems

Write c programme as per the Question statement-

Q1(a). Write a C programme where after fork(), parent process waits for termination of child process
and

Child process execute following code-

{ printf("child pid %u its parent pid %u \n",getpid(),getppid());

execl("/bin/ls","ls",NULL) ; // repalce prg image of child with ls command

exit(200);

Parent waits for the Child process termination using wait()

Q1(b). Write a C programme where after fork(),Parent process creates multiple children and then
wait for all of them.

(parent process waits till wait() returns -1)

do{waitch=wait(&status);}while(waitch!=childid); //wait for termination of specific child process


whoes pid is childid

(waitch is pid_t type and status is int type variable)

Parent process prints return status of the Child process

( To display the return code received by shell(bash), typr at prompt "echo $?" just after the
completion of the current command)

Q2(a). Write a C programme where after fork(),Parent and Child processes execute different
commands

(provide the path of the command in parameter).

Run in Child process “ls -a -l” (Hint : execl("/bin/ls","ls","-l","-a",NULL); )

("/bin/ls" is path ; "ls" is file ; "-l","-a" are parameters)

Run in Parent process “date” (Hint : execl("/bin/date","date",NULL); )


Q2(b). Write a C programme where after fork(),Parent and Child processes execute different
commands

(use default path of the command, as in PATH).

Run in Child process “ls -a -l” (Hint : execlp("ls","ls","-l","-a",NULL); )

( "ls" is to be searched in the directories specified by the PATH environment variable;

"ls" is file ; "-l","-a" are parameters)

Run in Parent process “date” (Hint : execlp("date","date",NULL); )

(In Q2(b) execlp finds the path of the file from environment variable (can check typing "$echo
PATH"), so full path of the command is not needed )

Q3. Write a C programme where after fork(),Child process executes the statement

execl("lab-3-1a","lab-3-1a",NULL);

(assuming output file Q1(i) of lab-sheet-3 is lab-3-1a)

(you can use absolute path with execlp("/home/os24/23uecxxxx/lab-3-1a","lab-3-1a",NULL) )

Q4. Write a C programme where after fork(),Child process runs prg "lab-4-3" using execl( );

//use appropriate parameters in execl()

(assuming binary file of Q3 in this sheet is lab-4-3)

Q5. Write a C programme that returns number of command line input(strings) entered and their
value.

(Hint: Command Line input- 1234 abcd my name "my name")

Hint: variable argc returns number of string passed to programme as CLI and argv[i] is used to read
string value of CLI.

(argv[0] gives the name of the programme itself.)

Q6. (i) Repeat Q2b but read execl() parameters from command line.

(ii) Repeat Q4 but read execl() parameters from command line.

Q7. Write a programme that reads user entered command from command line (second argument)
and executes it

using function system instead execl(). In case command needs paramerets then enclose command in
" " in system().
(a)run long list command from this programme (command line input "ls -al")

(b) try using "cd .."

check whether cwd(current working directory) has changed directory.(Think its reason if not)

(c) repeat (b) using chdir() instead system()

(run above programe where system()is used, in background (using &) and then run ps -f which
displays forked processes)

Q8. Write a programme that removes its binary file from the folder.

(use remove command in system function)

=========================

Hint:

Q1. Use waitpid() instead (as explained in lab-sheet-3)-

The waitpid() system call suspends execution of the calling process until particular child process

specified by pid argument has changed state. By default, waitpid() waits only for

terminated children, but this behavior is modifiable via the options argument.

pid_t waitpid(pid_t pid, int *status, int options)

take value of option 0

The value of pid can be:

-1 meaning wait for any child process.

> 0 meaning wait for the child whose process ID is equal to the value of pid.

If status is not NULL, wait() and waitpid() store status information in the int variable to

which it points to.

to wait for specific pid (the child process)

pid_t waitpid(pid_t pid, int *status, int options);

cpid= waitpid(pid,&status,0);// waits for specific child whose pid is "pid" and returns value is status

if(WIFEXITED(status) ) printf("exit code %d\n",WEXITSTATUS(status));


Q1b- (one possible solution)

child code-

for (j = 1; j < 3; j++) { // Create children

switch (fork()) {

case 0: // next child

printf(" child %d started with PID %ld, sleeping \n", j, (long) getpid());

sleep( 1+j*2 );//varied sleep time

exit(EXIT_SUCCESS);

default: break; // Parent just continues around loop

}}

parent code-

for (;;) { // Parent waits for each child to exit

childpid = wait(NULL);

if (childpid == -1) { printf("No more child \n"); exit(EXIT_SUCCESS);}

printf(" wait() returned child PID %ld \n",(long) childpid);

example of ececv()-

array of null terminated string having command and its switches

char *mycmd[] = { "ls", "-l","-a", NULL };

execv ("/bin/ls", cmd);

Q5. To display commandline input(CLI) string

use in programe-

int main(int argc, char *argv[])

argc gives number of commandline input strings and argv[i] points the ith string

these parameters are passed when the programme is invoked


for example-

$ ./lab-4-6 my string 1234 "and more"

here argc is 5, argv[0]=./lab-4-6, ......

following code display the CLI strings-

while(argc-- > 0)

printf(" cli string i %d: %s \n",i,argv[i++]);

( CLI inputs are stored in string which needs to be converted properly before use, if input is ASCII
number)

In case environment parametrs of system passed to child

int main(int argc, char *argv[], char *env[])

you may print env[] for i=0;i<n , let say n is 10

Q7. system(command) executes a command specified in "command" by calling "/bin/sh -c


command", and returns after

the "command" has been completed. During execution of the "command", SIGCHLD will be blocked,

and SIGINT and SIGQUIT will be ignored.

chdir() changes working directory to specified path. So use chdir(path) instead system().

Where path is the string of destination directory. For example chdir("..") change directory to
parent(one level up).

verify the effect of chdir("..") ---- use printf("%s\n ", getcwd(s,100)); before and after changing
directory using chdir().... use char s[100] as buffer

(cd is internal command of shell . So system("cd ..") does not change cwd.)

Q8. Using system command. Use snprintf(cmd, sizeof(cmd), "rm %s",argv[0]) to append parameter
with command to be executed.

where char cmd[256];

You might also like