【问题标题】:C synchronize processes using signalC 使用信号同步进程
【发布时间】:2015-05-06 05:39:04
【问题描述】:

好的,所以我正在尝试自学如何发送信号,但我遇到了一个问题,我无法弄清楚我做错了什么。现在发生的事情是:它正在执行父级然后转到子级然后返回到父级.. 它没有做我想要它做的事情,即执行父级(用户定义它运行的时间量)然后将其杀死,然后转到子节点并在相同的时间内自行运行。

#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++;
        }
}

我想要它做的是:

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

非常感谢任何帮助!

【问题讨论】:

    标签: c linux signals system-calls fork


    【解决方案1】:

    你已经得到了大部分的碎片,它们只需要稍微重新排序。

    • 在使用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
        }
    }
    

    【讨论】:

    • 谢谢!实际上,我最终有 3 个叉子(父母、孩子和孙子)来完成同样的事情!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-04-13
    • 2011-09-06
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多