Below is the working solution for you problem.
#include <stdio.h> #include <signal.h> #include <unistd.h> #include <sys/wait.h> int main() { int pid = fork(); if (pid < 0) { printf("error"); return -1; } if (pid == 0) { raise(SIGSTOP); // Stopping the execution of child process printf(" Pong"); } else { waitpid(pid, NULL, WUNTRACED); // Wait until the child execution is stopped printf("Ping"); kill(pid, SIGCONT); // resume child process } return 0; }
Explanation:
When we use fork, we can't predict which process will execute first. Based on scheduling algorithm either PARENT process or CHILD process may execute.
In the above code, we have two scenarios :
Scenario 1: If child executes first, I am stopping/pausing the child execution using the SIGSTOP. So when child execution is paused PARENT process will get scheduled and will print "Ping" message. After printing the ping message, I am giving the resume/CONTINUE signal to child. Now child prints "Pong"
Scenario 2: IF parent executes first, I am making parent to wait until the child process is stopped. Because before parent prints "ping", context switch might happen suddenly and message in child process might be printed. So to avoid that I am waiting until the child moved to STOP state. Once the child is in STOPPED , Parent prints "ping" and will RESUME the child and child prints "pong".
Hope you understood my explanation...
killfunction sends a signal to another process