我必须在Linux中将任务作为进程创建,但我不希望在创建所有进程之前执行该进程。所以我想到在创建后立即将进程移动到等待队列并等待直到创建所有进程。
#include <unistd.h> /* Symbolic Constants */
#include <sys/types.h> /* Primitive System Data Types */
#include <errno.h> /* Errors */
#include <stdio.h> /* Input/Output */
#include <stdlib.h> /* General Utilities */
#include <pthread.h> /* POSIX Threads */
#include <string.h> /* String handling */
#include <sched.h>
#include <linux/kernel.h>
#include <time.h>
#include <sys/resource.h>
#include <stddef.h>
#include <linux/sched.h>
#include <linux/wait.h> /* for wait_event_interruptible() & wake_up_interruptible() */
int done = 0;
static DECLARE_WAIT_QUEUE_HEAD(queue);
int main()
{
int pid1, pid2;
if ((pid1 = fork()) < 0) //create a child process
exit(1);
if ((pid2 = fork()) < 0) //create a child process
exit(1);
if (pid1 == 0) //child process
{
wait_event_interruptible(queue, done == 2);
printf("child 1\n");
}
else //parent process
{
done = done+1;
wake_up_interruptible(&queue);
}
if (pid2 == 0) //child process
{
wait_event_interruptible(queue, done == 2);
printf("child 2\n");
}
else //parent process
{
done = done+1;
wake_up_interruptible(&queue);
}
return 0;
}
但是当我尝试这个示例代码时,它会显示这些错误。
$ gcc -Wall try.c
try.c:18:8: warning: type defaults to ‘int’ in declaration of ‘DECLARE_WAIT_QUEUE_HEAD’ [-Wimplicit-int]
try.c:18:1: warning: parameter names (without types) in function declaration [enabled by default]
try.c: In function ‘main’:
try.c:33:6: warning: implicit declaration of function ‘wait_event_interruptible’ [-Wimplicit-function-declaration]
try.c:33:31: error: ‘queue’ undeclared (first use in this function)
try.c:33:31: note: each undeclared identifier is reported only once for each function it appears in
try.c:39:2: warning: implicit declaration of function ‘wake_up_interruptible’ [-Wimplicit-function-declaration]
try.c: At top level:
try.c:18:8: warning: ‘DECLARE_WAIT_QUEUE_HEAD’ declared ‘static’ but never defined [-Wunused-function]
当我检查$ man wait_event_interruptible时,它显示“没有手动输入wait_event_interruptible”。因此库中缺少API。如何将其添加到库中?提前谢谢。
答案 0 :(得分:2)
wait_event_interruptible(),wake_up_interruptible()是用于创建和使用等待队列的内核API。你不能使用来自用户的那些!
如果我正确理解您的目的,您需要做的是创建N个流程障碍。如果您知道进程数(N),则可以轻松使用信号量:使用零初始化信号量,所有进程调用down(),最后一个进程调用()N次。您也可以使用消息队列。
您也可以使用Linux API作为障碍:pthread_barrier_wait和pthread_barrier_init,但我之前没有使用过它。