在liunxC下的编程求解
1.有三个进程
2.其中一个进程等待其它两个进程的信号,当两个来了就打印出一句“Engine is running”
3.另外两个进程每隔10秒向上一个进程发信号,并且打印“Oil is ready” “Power is on”
#include <signal.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
void process_start()
{
pid_t oil_process;
pid_t power_process;
if((oil_process=fork())==0)
{
sleep(10);
kill(engine_process,SIGUSR1);
printf("Oil is ready\n");
exit(0);
}
if((power_process=fork())==0)
{
sleep(10);
kill(engine_process,SIGUSR2);
printf("Power is on\n");
exit(0);
}
}
static void sig_usr(int signo)
{
if((signo==SIGUSR1) && (signo==SIGUSR2))
{
printf("Engine is running \n");
}
}
main(void)
{
struct sigaction act;
act.sa_handler=sig_usr;
act.sa_flags=0;
pid_t engine_process;
sigaction(SIGUSR1,&act,NULL);
sigaction(SIGUSR2,&act,NULL);
if((engine_process=fork())==0)
{
process_start();
exit(0);
}
}
直接写的,求纠正!
[解决办法]
- C/C++ code
static void sig_usr(int signo){ static unsigned char s_flags = 0x00; if (signo == SIGUSR1) { s_flags |= 0x01; } else if (signo == SIGUSR2)) { s_flags |= 0x02; } if (0x03 == (s_flags & 0x03)) { s_flags = 0x00; printf("Engine is running \n"); }}
[解决办法]
太可怕了。。。 代码到你们这里就变的那么不可控。。。能自己看看man手册吗- -。。
这个代码我测过了,可以正常工作。
- C/C++ code
#include <stdio.h>#include <stdlib.h>#include <string.h>#include <signal.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>void sig_handler(int signo) { switch (signo) { case SIGUSR1: fprintf(stderr, "A is ready\n"); break; case SIGUSR2: fprintf(stderr, "B is ready\n"); break; default: break; }}int main(int argc, char* const argv[]) { struct sigaction act; sigset_t mask; bzero(&act, sizeof(act)); sigemptyset(&mask); sigaddset(&mask, SIGUSR2); act.sa_handler = sig_handler; act.sa_mask = mask; if (sigaction(SIGUSR1, &act, NULL) == -1) { fprintf(stderr, "ERROR:sigaction SIGUSR1\n"); return -1; } sigemptyset(&mask); sigaddset(&mask, SIGUSR1); act.sa_mask = mask; if (sigaction(SIGUSR2, &act, NULL) == -1) { fprintf(stderr, "ERROR:sigaction SIGUSR2\n"); return -1; } int ndx; for (ndx = 0; ndx != 2; ++ ndx) { pid_t pid; int sig[2] = {SIGUSR1, SIGUSR2}; if ((pid = fork()) == -1) { fprintf(stderr, "ERROR:fork\n"); return -1; } else if (pid == 0) { int times = 0; for ( ; times != 5; ++ times) { kill(getppid(), sig[ndx]); sleep(10); } exit(0); } } int ret; pid_t pid; for (ret = 0; ret != 2; ) { pid = wait(NULL); if (pid != -1) { ++ ret; } } return 0;}