Wait System Call Practical No 3 Wait System

  • Slides: 7
Download presentation
Wait System Call Practical No 3

Wait System Call Practical No 3

Wait System Call in C • A call to wait() blocks the calling process

Wait System Call in C • A call to wait() blocks the calling process until one of its child processes exits or a signal is received. • After child process terminates, parent continues its execution after wait system call instruction. • Child process may terminate due to any of these: • It calls exit(); • It returns (an int) from main • It receives a signal (from the OS or another process) whose default action is to terminate.

C program to demonstrate working of wait() #include<stdio. h> #include<stdlib. h> printf("Parent pid =

C program to demonstrate working of wait() #include<stdio. h> #include<stdlib. h> printf("Parent pid = %dn", getpid()); #include<sys/wait. h> printf("Child pid = %dn", cpid); #include<unistd. h> int main() return 0; { } pid_t cpid; if (fork()== 0) exit(0); /* terminate child */ else cpid = wait(NULL); /* reaping parent */

Another C program to demonstrate working of wait() #include<stdio. h> #include<sys/wait. h> #include<unistd. h>

Another C program to demonstrate working of wait() #include<stdio. h> #include<sys/wait. h> #include<unistd. h> int main() { if (fork()== 0) printf("HC: hello from childn"); else { printf("HP: hello from parentn"); wait(NULL); printf("CT: child has terminatedn"); } printf("Byen"); return 0; }

waitpid-example. c #include <sys/types. h> #include <sys/wait. h> #include <unistd. h> #include <stdio. h>

waitpid-example. c #include <sys/types. h> #include <sys/wait. h> #include <unistd. h> #include <stdio. h> #include <stdlib. h> int main(void) { pid_t pid; pid = fork(); if (pid < 0) { perror("fork failed"); exit(1); } if (pid == 0) { int i; for (i = 3; i > 0; i--) { printf("This is the childn"); sleep(1); } exit(3); } else { int stat_val; waitpid(pid, &stat_val, 0); //waitpid(pid, &stat_val); printf("exit code: %d, signal: %d, raw stat_val: 0 x%x %d"); } return 0; }

 • • *get_exitstatus. c*/ #include <unistd. h> #include <stdio. h> #include <stdlib. h>

• • *get_exitstatus. c*/ #include <unistd. h> #include <stdio. h> #include <stdlib. h> printf("Child: %d: I'm the childn", pid, c_pid); printf("Child: sleeping for 2 -seconds, then exiting with status 12n"); //sleep for 2 seconds sleep(2); //exit with statys 12 exit(12); }else if (c_pid > 0){ //parent //waiting for child to terminate pid = wait(&status); • #include <sys/types. h> • #include <sys/wait. h> • int main(){ if ( WIFEXITED(status) ){ printf("Parent: Child exited with status: %dn", WEXITSTATUS(status)); } • pid_t c_pid, pid; • int status; }else{ //error: The return of fork() is negative perror("fork failed"); _exit(2); //exit failure, hard } • c_pid = fork(); //duplicate • if( c_pid == 0 ){ • //child • pid = getpid(); } return 0; //success