【发布时间】: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