2つの異なる端末で実行中のプロセス(サーバーとクライアント)を処理する必要があります。クライアントはユーザー入力を読み取り、それをファイル(hello.txt)に保存し、SIGUSR1に信号を送り、スリープします。次に、サーバーはウェイクアップし、ファイル(hello.txt)を読み取り、それを印刷し、クライアントに動作したことを通知してからスリープします。次に、クライアントはウェイクアップし、成功したことを出力して、別のユーザー入力を待ちます。
後でそれ以上のものがありますが、これが私が現在達成しようとしているすべてです。2つの別々の無関係なプロセス間でsigactionとSIGUSR1を使用した例を見つけるのに苦労しました。これが私がこれまでに持っているコードです:
server.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;
}
client.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を知る必要がありますか?私は完全に間違ったことをしているだけですか?