【发布时间】:2019-11-15 05:10:36
【问题描述】:
我需要一些 C 代码方面的帮助。
基本上我有n 执行一些代码的进程。一旦几乎完成,我希望“管理器进程”(这是主要功能)向每个n 进程发送一个int 变量,每个进程可能不同。
我的想法是在所有进程开始后signal(handler_function, SIGALRM)。当进程几乎完成时,它使用kill(getpid(), SIGSTOP) 以等待Manager Process。
在SIM_TIME 秒过去后,handler_function 在Message Queue 上发送int 变量,然后使用kill(process_pid, SIGCONT) 来唤醒等待进程。这些进程在被唤醒后应该从Message Queue 接收到int 变量,打印它并简单地终止,让Manager Process 再次获得控制权。
这里有一些代码:
/**
* Child Process creation using fork() system call
* Parent Process allocates and initializes necessary variables in shared memory
* Child Process executes Student Process code defined in childProcess function
*/
pid_t runChild(int index, int (*func)(int index))
{
pid_t pid;
pid = fork();
if (pid == -1)
{
printf(RED "Fork ERROR!\n" RESET);
exit(EXIT_FAILURE);
}
else if (pid == 0)
{
int res = func(index);
return getpid();
}
else
{
/*INSIGNIFICANT CODE*/
currentStudent = createStudent(pid);
currentStudent->status = FREE;
students[index] = *currentStudent;
currentGroup = createGroup(index);
addMember(currentStudent, currentGroup);
currentGroup->closed = FALSE;
groups[index] = *currentGroup;
return pid;
}
}
每个进程执行的代码
/**
* Student Process Code
* Each Student executes this code
*/
int childProcess(int index)
{
/*NOTICE: showing only relevant part of code*/
printf("Process Index %d has almost done, waiting for manager!\n", index);
/* PROGRAM GETS STUCK HERE!*/
kill(getpid(), SIGSTOP);
/* mex variable is already defines, it's a struct implementing Message Queue message struct*/
receiveMessage(mexId, mex, getpid());
printf(GREEN "Student %d has received variable %d\n" RESET, getpid(), mex->variable);
}
处理函数:
* Handler function
* Will be launched when SIM_TIME is reached
*/
void end_handler(int sig)
{
if (sig == SIGALRM)
{
usleep(150000);
printf(RED "Time's UP!\n" RESET);
printGroups();
for(int i = 0; i < POP_SIZE; i++){
mex->mtype = childPids[i];
mex->variable = generateInt(18, 30);
sendMessage(mexId, mex);
//childPids is an array containing PIDs of all previously launched processes
kill(childPids[i], SIGCONT);
}
}
我希望我的代码是可以理解的。
我有一个问题,使用提供的代码,整个程序卡在kill(getpid(), SIGSTOP) 系统调用。
我还尝试在终端中启动ps,但未检测到活动进程。
我认为handler_function 出于某种原因没有发送kill(childPids[i], SIGCONT) 系统调用。
知道如何解决这个问题吗?
谢谢
【问题讨论】:
-
父级不能初始化一个大小为n的int数组(每个子进程一个位置)发送整数,然后每个子进程从这个数组中获取值吗?
-
我的目标是确保管理器进程可以与任何单个进程通信。您建议的解决方案无济于事。
标签: c fork message-queue