0% found this document useful (0 votes)
9 views2 pages

Program-1-1

Uploaded by

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

Program-1-1

Uploaded by

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

/*1.

Develop a c program to implement the Process system calls (fork (), exec(),
wait(), create process,terminate process)*/

a. Single process

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main() {
pid_t child_pid;
int status;
child_pid = fork();
if (child_pid < 0) {
perror("Fork failed");
exit(1);
} else if (child_pid == 0) {
printf("Child process (PID: %d) is running.\n", getpid());
execlp("/bin/ls", "ls", "-l", NULL);
perror("Exec failed");
exit(1);
} else {
printf("Parent process (PID: %d) created a child (PID: %d).\n", getpid(),
child_pid);
wait(&status);

if (WIFEXITED(status)) {
printf("Child process (PID: %d) exited with status %d.\n", child_pid,
WEXITSTATUS(status));
} else {
printf("Child process (PID: %d) did not exit normally.\n", child_pid);
}
}

return 0;
}

b. Multiple processes

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<unistd.h>

void waitexample() {
int i, stat;
pid_t pid[5];

for (i = 0; i < 5; i++) {


if ((pid[i] = fork()) == 0) {
sleep(1);
exit(100 + i);
}
}
for (i = 0; i < 5; i++) {
pid_t cpid = waitpid(pid[i], &stat, 0);
if (WIFEXITED(stat))
printf("Child %d terminated with status: %d\n", cpid,
WEXITSTATUS(stat));
}
}

int main() {
waitexample();
return 0;
}

You might also like