C使用信号同步进程

Fad*_*adi 2 c linux fork signals system-calls

好吧所以我正在努力教自己如何做信号,我遇到了一个打嗝,我无法弄清楚我做错了什么.现在正在发生的事情是:它正在执行父级然后转到子级然后再回到父级..它没有做我想要它做的事情,即执行父级(用户定义它运行的时间)然后杀死它然后去孩子并在相同的时间运行自己.

#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++;
        }
}
Run Code Online (Sandbox Code Playgroud)

我想要它做的是:

hello 0
hello 1
hello 2
hello 3
hello 4
Switching
hi 0
hi 1
hi 2
hi 3
hi 4
Run Code Online (Sandbox Code Playgroud)

任何帮助深表感谢!

use*_*109 6

你有大部分的东西,他们只需要重新排序一点.

  • 在使用之前在两个进程中安装信号处理程序 kill
  • 父母应该在发信号通知孩子之前完成打印
  • 孩子完成打印后可以发出信号

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
    }
}
Run Code Online (Sandbox Code Playgroud)