【发布时间】:2014-09-07 03:19:02
【问题描述】:
我是一个非常初学者的程序员,我正在开发一个客户端服务器程序,在 Ubuntu 中。这段代码属于我的serverfile,我想实现一个信号SIGALRM但我只是不知道如何正确地做到这一点。
我的目标是:在我调用信号alarm(ans.game_time)的代码部分,我想运行那个函数Time,这个函数应该等待ans.game_time秒,在这些秒内,玩家应该加入游戏(这最后一部分还没有实现,“播放”命令)。
结构:
typedef struct request req;
struct request
{
char str[256];
int client_pid;
int login; // In case of client, to identify if is logged
int whois; // To identify who is the client and the server
};
typedef struct answer ans;
struct answer
{
char str[256];
int server_pid;
int type;
int login;
int num_users;
char game_name[25];
int game_time;
int game_users[4];
};
服务器文件:
#include "header"
int array_client_PID[4], num_users = 0;
int GAME_STATUS = 0;
void Time(int sign)
{
signal(SIGALRM, Time);
alarm(3);
printf("I'm Alive");
}
int main(){
int fifo_1,fifo_2, pid, i, number_args;
char FIFO_CLIENT[20], command[20], arg_1[20], arg_2[20];
struct request req;
struct answer ans;
signal(SIGALRM, Time);
do{
read(fifo_1, &req, sizeof(req)); // Read request
if(req.login == 1) // USER REGISTATION: If logged
{
number_args = sscanf(req.str, "%s %s %s", command, arg_1, arg_2);
if(strcasecmp(command, "new") == 0)
{
if(GAME_STATUS == 0)
{
ans.game_time = atoi(arg_2); // Converts the string into a integrer time game
strcpy(ans.game_name, arg_2); // Put the name of the game on the structure
ans.game_users[0] = req.client_pid; // Put on the users avaiable to play, the name of the game creator
alarm(ans.game_time);
//CreateGame(ans); // not implemented yet
}
else
{
strcpy(ans.str,"One game is in execution. Just wait...\n");
}
}
if(GAME_STATUS== 1) // GAME STATUS: ON
{
printf("INSIDE GAME_STATUS 1\n");
// Receive commands inside the game
}
}
sprintf(FIFO_CLIENT, "FIFO_%d", req.client_pid); //2nd FIFO name with client PID
fifo_2=open(FIFO_CLIENT, O_WRONLY); // Open 2nd FIFO to answer
write(fifo_2, &ans, sizeof(ans)); // Write an answer
}while(1);
}
我试图了解它是如何正常工作的,但这个信号让我很困惑。
【问题讨论】:
-
阅读signal(7) 和poll(2)。你可能想
poll。另见Advanced Linux Programming -
正如@BasileStarynkevitch 暗示的那样,您根本不应该为此使用信号。正确使用信号对于初学者来说不是任务,大多数应用程序都不需要它。
-
@BasileStarynkevitch 我真的需要在这部分代码中使用信号,我的教授说这是强制性的。
-
@JohnZwinck 实际上信号对我来说并不新鲜,但是这个特定的信号,很难理解它是如何工作的