Skip to content
Advertisement

Communication between two processes without using fork()

I’m trying to do a ping pong exercise, I ask for guidance / direction but not a solution so I can learn.

Workspace: ubuntu 19

Language: C.

The task is like this:

  • Do not use () fork
  • The ping process is waiting for a signal
  • The Pong process gets the Ping PID from the command line as an argument
  • Pong should send SIGUSER1 signal to ping
  • Ping returns a signal SIGUSER2 to pong and so on …
  • run 2 processes from gdb.

My questions are like this:

  1. How do I pass the pid as a command line argument?
  2. How do I read the PID in the second process?

Advertisement

Answer

so, the question makes perfect sense. This is an exercise in using signals and signal handlers.

Pong.c will have something like (but you should add error handling yourself if, for example, there is no pid):

#include <sys/types.h>
#include <unistd.h>
#include <signal.h>

void sigHandler( int signo, siginfo_t *siginfop, void *context)
{
   /* send another signal back to ping, you dont need the pid you read from cmd line */ 
   union sigval sv;
   if( siginfop != NULL )
       sigqueue( siginfop->si_pid, SIGUSR1, sv)
 }
      
void main( int argc, const char *argv[] )
{
   int ping_pid = atoi(argv[1]);
   
   /* this is for receiving signals */
   struct sigaction sa;
   sa.sigaction = sigHandler;
   sigemptyset(&sa.sa_mask);
   sa.sa_flags = SA_NODEFER | SA_SIGINFO;
   
   /* you send SIGUSR1 from pong; you'll receive SIGUSR2 from ping */
   if( sigaction(SIGUSR2, &sa, NULL) == -1) perror("sigaction");
   

  /* this is for sending the first signal */
   union sigval sv;
   
   if( sigqueue( ping_pid, SIGUSR1, sv) == -1 ) perror("sigqueue")
   /*
    do something
    while u wait
   */
  }

And for the other program, in ping.c you do the same, except you dont read a pid off the command line, you just wait for the other processes signal; and the signal id’s are the other way round (or however you need it).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement