0% found this document useful (0 votes)
44 views4 pages

Assignment 1

This document contains code snippets demonstrating the fork(), exec(), and wait() system calls in C. The fork() code creates a parent and child process, with each printing its process ID. The exec() code shows the parent process launching /bin/ls via execl() and waiting for it to complete. The wait() code demonstrates the parent process waiting for the child to finish before continuing.
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)
44 views4 pages

Assignment 1

This document contains code snippets demonstrating the fork(), exec(), and wait() system calls in C. The fork() code creates a parent and child process, with each printing its process ID. The exec() code shows the parent process launching /bin/ls via execl() and waiting for it to complete. The wait() code demonstrates the parent process waiting for the child to finish before continuing.
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/ 4

Fork()

#include<stdio.h>

#include<stdlib.h>

#include<unistd.h>

#include<sys/types.h>

int main(int argc, char **argv)

pid_t pid;

pid = fork();

if(pid==0)

printf("It is the child process and pid is %d\n",getpid());

exit(0);

else if(pid > 0)

printf("It is the parent process and pid is %d\n",getpid());

else

printf("Error while forking\n");

exit(EXIT_FAILURE);

return 0; } .
exec()

#include <stdio.h>

#include <unistd.h>

#include <stdlib.h>

#include <sys/types.h>

#include <sys/wait.h>

main(void) {

pid_t pid = 0;

int status;

pid = fork();

if (pid == 0) {

printf("I am the child.");

execl("/bin/ls", "ls", "-l", "/home/ubuntu/", (char *) 0);

perror("In exec(): "); }

if (pid > 0) {

printf("I am the parent, and the child is %d.\n", pid);

pid = wait(&status);

printf("End of process %d: ", pid);

if (WIFEXITED(status)) {
printf("The process ended with exit(%d).\n", WEXITSTATUS(status));}

if (WIFSIGNALED(status)) {

printf("The process ended with kill -%d.\n", WTERMSIG(status));}}

if (pid < 0) {

perror("In fork():");}

exit(0);}

wait()

#include<stdio.h> // printf()

#include<stdlib.h> // exit()

#include<sys/types.h> // pid_t

#include<sys/wait.h> // wait()

#include<unistd.h> // fork

int main(int argc, char **argv){

pid_t pid;

pid = fork();

if(pid==0){

printf("It is the child process and pid is %d\n",getpid());

int i=0;

for(i=0;i<8;i++){
printf("%d\n",i);}

exit(0);}

else if(pid > 0){

printf("It is the parent process and pid is %d\n",getpid());

int status;

wait(&status);

printf("Child is reaped\n");}

else{

printf("Error in forking..\n");

exit(EXIT_FAILURE);}

return 0;}

You might also like