C synchronize processes using signal

隐身守侯 提交于 2019-12-07 19:44:49

问题


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:


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


来源:https://stackoverflow.com/questions/28867909/c-synchronize-processes-using-signal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!