CS Electrical And Electronics
@cselectricalandelectronics

Wiatpid usage code in linux operating system

All QuestionsCategory: Operating SystemWiatpid usage code in linux operating system
Anonymous asked 2 years ago
1 Answers
Anonymous answered 2 years ago

Wiatpid usage

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

int main() {
pid_t ret;
int i, status;
printf("welcome..pid=%d\n", getpid());
ret = fork();
if (ret < 0) {
perror("fork");
exit(1);
}
if (ret == 0) {
printf("child--welcome,pid=%d,ppid=%d\n", getpid(), getppid());
for (i = 1; i <= 5; i++) {
printf("child--pid=%d,ppid=%d\n", getpid(), getppid());
usleep(100);
}
// exit(5);
exit(0);
} else // ret>0
{
printf("parent--hello,pid=%d,ppid=%d\n", getpid(), getppid());
// some work by parent
waitpid(-1, &status, 0); // wait(&status);
printf("parent--child exit status=%d\n", WEXITSTATUS(status));
}
return 0;
}

 
Notes
 

  • Blocks parent process till completion of child process
  • Collect exit status of child
  • Cleans some pending resources of child (else child will become Zombie)
  • waitpid paramaters
    • 1st param : pid of child process waiting for, -1 means any one child
    • 2nd param : status of terminated child (pass by address)
    • 3rd param : flags
  • Macros WEXITSTATUS, WIFEXITED to check exit status, normal/abnormal termination

 
Observations & Understanding
 

  • Do child process is re parenting to init (adoption by init) after adding waitpid?
  • Meaning of 1st parameter to waitpid : -1
  • More analysis on child exit status thru waitpid –  WIFEXITED, WIFSIGNALED etc.
  • Observations of different ways in which process terminates
    • Normal and Success – exit child with zero
    • Normal and Failure – exit child with non zero, +ve value
    • Abnormal Termination (Try divided by zero or null pointer difference in child)