Lab-1
Lab-1
After the successful call to fork(), two processes are created; the
parent and the child process.
It's important to note that after the fork(), both the parent and
child processes continue executing from the point of the fork()
call.
#include <stdio.h>
int main()
{
printf("Hello world\n");
return 0;
Hello world
}
#include <stdio.h>
int main()
{
printf("Hello world\n");
fork();
return 0;
}
#include <stdio.h>
int main()
{
fork();
printf("Hello world\n");
return 0;
}
#include <stdio.h>
#include <unistd.h>
int main()
{
printf("Hello world\n");
printf("Hello world!, process_id(pid) = %d \n",getpid());
fork();
printf("Hello world\n");
printf("Hello world!, process_id(pid) = %d \n",getpid());
return 0;
}
Hello world
Hello world!, process_id(pid) = 6298
Hello world
Hello world!, process_id(pid) = 6298
Hello world
Hello world!, process_id(pid) = 6299
The child process is an exact copy of the parent, with its own unique process
identifier (PID).
It's important to note that after the fork(), both the parent and child processes
continue executing from the point of the fork() call.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t p = fork();
if(p<0)
{
perror("fork fail");
exit(1);
} if(p==0)
{
printf("It is the child process,process_id(pid) = %d \n",getpid());
}
else
{
printf(“Parent process!, process_id(pid) = %d \n",getpid());
}
return 0;
}
• Parent process!, process_id(pid) = 6357
• It is the child process,process_id(pid) = 6358
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
fork();
fork();
????????????????
fork();
printf("hello\n");
return 0;
}
Exec()
• The exec family of functions replaces the current running process with a new
process.
• It can be used to run a C program by using another C program. It comes under
the header file unistd.h. There are many members in the exec family which
are shown below with examples.
call replaces the image of the current process with a new process image specified by
the path i.e. the current process code gets replaced by a new process code
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{ pid_t pid;
printf("Parent process (PID: %d)\n", getpid());
// Create a child process
pid = fork();
if (pid < 0)
{
perror("Fork failed");
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
// Child process
printf("Child process (PID: %d), Parent PID: %d\n", getpid(), getppid());
// Execute a new program in the child process
execl("/bin/ps", "ps", NULL); // The code below will only execute if execl fails
perror("Exec failed");
exit(EXIT_FAILURE);
}
else
{
// Parent process
printf("Parent process, waiting for the child...\n");
// Wait for the child to complete
wait(NULL);
printf("Child process completed.\n");
}
return 0;
}