1

I need to write "Ping pong" to command line using Linux processes in C (parent prints "Ping ", its child - "pong"), but I have no idea how to send signal from parent to child.

#include <stdio.h> #include <signal.h> #include <unistd.h> void childSignalHandler(int signal) { puts("pong"); } void parentSignalHandler(int signal) { puts("Ping "); } int main() { int pid = fork(); if (pid < 0) { printf("error"); return -1; } if (pid == 0) { signal(SIGUSR2, childSignalHandler); } else { signal(SIGUSR1, parentSignalHandler); raise(SIGUSR1); } return 0; } 
1
  • The kill function sends a signal to another process Commented Mar 19, 2020 at 13:12

2 Answers 2

2

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...

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I had no clue that kill() does anything excepting termination of the process
0

You are looking for pipes, essentially they constitute am one way connection between two processes. Think of them as a virtual file that can be used to parse information.

Heres a tutorial to get you started

https://www.geeksforgeeks.org/pipe-system-call/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.