我必须在两个不同的终端上运行进程(服务器和客户端)。客户端读取用户输入,将其保存到文件(hello.txt),发出 SIGUSR1 信号,然后休眠。服务器然后唤醒,读取文件(hello.txt),打印它,向客户端发出信号它工作,然后休眠。客户端然后唤醒,打印成功,然后等待另一个用户输入。
稍后还有更多内容,但这就是我目前想要完成的全部。我很难在两个独立的、不相关的进程之间找到使用 sigaction 和 SIGUSR1 的示例。这是我到目前为止的代码:
服务器.c
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
volatile sig_atomic_t myFlag = 0;
static void myHandler(int);
struct sigaction newAction, oldAction;
int main(int argc, char* argv[])
{
//setup signal stuff
sigset_t zeromask;
sigemptyset(&newAction.sa_mask);
sigemptyset (&oldAction.sa_mask);
sigemptyset(&zeromask);
newAction.sa_flags = 0;
newAction.sa_handler = myHandler;
sigaddset (&newAction.sa_mask, SIGUSR1);
if ( sigaction(SIGUSR1, &newAction, &oldAction))
return;
for ( ; ; ) {
//Loop
//This is so I can manually enter the pid into the client
printf("%d\n",getpid());
while(myFlag == 0)
sigsuspend (&zeromask);
myFlag = 0;
printf("Got signal, process it\n");
//signal occured process it
}
sigprocmask (SIG_SETMASK, &oldAction.sa_mask, NULL);
exit(0);
}
static void myHandler(int sigNo) {
myFlag = 1;
printf("finally made it");
sigprocmask (SIG_BLOCK, &newAction.sa_mask, &oldAction.sa_mask);
return;
}
客户端.c
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
volatile sig_atomic_t myFlag = 0;
static void myHandler(int);
struct sigaction newAction, oldAction;
int main(int argc, char* argv[])
{
printf("begin\n");
//Signal stuff
sigset_t zeromask;
sigemptyset(&newAction.sa_mask);
newAction.sa_flags = 0;
newAction.sa_handler = myHandler;
sigemptyset (&oldAction.sa_mask);
sigemptyset(&zeromask);
sigaddset (&newAction.sa_mask, SIGUSR1);
if ( sigaction(SIGUSR1, &newAction, &oldAction))
return;
sigprocmask (SIG_BLOCK, &newAction.sa_mask, &oldAction.sa_mask);
//loop
for ( ; ; ) {
printf("This is where you would get user input\n");
//Signal Server
//For now I just manually enter the pid that was printed out when I ran server.c. This does not work and I do not think it is the right thing to do
kill(27514,SIGUSR1);
//loop while waiting for server to respond
while(myFlag == 0)
sigsuspend (&zeromask);
myFlag = 0;
printf("this is where you would process return signal\n");
//signal occured process it
}
sigprocmask (SIG_SETMASK, &oldAction.sa_mask, NULL);
exit(0);
}
static void myHandler(int sigNo) {
myFlag = 1;
sigprocmask (SIG_BLOCK, &newAction.sa_mask, &oldAction.sa_mask);
return;
}
现在,所有这些代码应该做的就是从客户端向服务器发送信号。从那里我将实施其余的。但是,这不起作用,我似乎无法弄清楚。
kill 是用来实现 SIGUSR1 的正确命令吗?我是否需要知道每个客户端和服务器的 PID 才能进行通信?我完全只是在做错事吗?