C synchronize processes using signal

2019-05-24 16:52发布

Okay so I am trying to teach myself on how to do signalling, and I came across a hiccup and I can't figure out what I'm doing wrong. What is going on right now is: it is executing the parent then goes to child and then back to parent.. It's not doing what I want it to do which is execute the parent (which the user defines the amount of time it runs) then kills it then go to child and run itself at the same amount of time.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h> // for wait
#include <sys/wait.h>  // for wait

void action(int);
void action(int dummy){
    sleep(1);
    printf("Switching\n");
}

int main(int argc, char *argv[]){
    pid_t pid;
    int m = atoi(argv[1]), i = 0, x = 0;
    if((pid=fork())>0){//parent
        sleep(1);
        while(i < m){
            printf("hello %d\n", x);
            x++;
            kill(pid, SIGUSR1);
            signal(SIGUSR1, action);
            pause();
            i++;
        }
    }

    else
        while(i < m){//child
            //waitpid(getppid(), &status, 0); // wait for parent
            signal(SIGUSR1, action);
            pause();
            printf("hi%d\n", x);
            x++;
            kill(getppid(), SIGUSR1);
            i++;
        }
}

What I want it to do is:

hello 0
hello 1
hello 2
hello 3
hello 4
Switching
hi 0
hi 1
hi 2
hi 3
hi 4

Any help is much appreciated!

1条回答
混吃等死
2楼-- · 2019-05-24 17:27

You've got most of the pieces, they just need to be reordered a little bit.

  • install the signal handler in both processes before using kill
  • the parent should finish printing before signaling the child
  • the child can signal back after its done printing

void action(int dummy)
{
    sleep(1);
    printf("Switching\n");
}

int main(int argc, char *argv[])
{
    int m = 3;
    if (argc == 2)
        m = atoi(argv[1]);

    pid_t pid = fork();         // create the child process
    signal(SIGUSR1, action);    // set up the signal handler for both parent and child

    if ( pid > 0 )              // the parent
    {
        for ( int i = 0; i < m; i++ )
        {
            sleep(1);
            printf("hello %d\n", i);
        }
        kill( pid, SIGUSR1 );   // signal the child
        pause();                // wait for the child to signal back
        printf("All done\n");
    }
    else                        // the child
    {
        pause();                // wait for the signal from the parent
        for ( int i = 0; i < m; i++ )
        {
            sleep(1);
            printf("hi %d\n", i);
        }
        kill(getppid(), SIGUSR1);   // signal the parent
    }
}
查看更多
登录 后发表回答