C synchronize processes using signal

冷暖自知 提交于 2019-12-06 09:16:47

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